Worker.php 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612
  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. declare(strict_types=1);
  15. namespace Workerman;
  16. use Exception;
  17. use stdClass;
  18. use Throwable;
  19. use Workerman\Connection\ConnectionInterface;
  20. use Workerman\Connection\TcpConnection;
  21. use Workerman\Connection\UdpConnection;
  22. use Workerman\Events\Event;
  23. use Workerman\Events\EventInterface;
  24. use Workerman\Events\Revolt;
  25. use Workerman\Events\Select;
  26. use Revolt\EventLoop;
  27. /**
  28. * Worker class
  29. * A container for listening ports
  30. */
  31. #[\AllowDynamicProperties]
  32. class Worker
  33. {
  34. /**
  35. * Version.
  36. *
  37. * @var string
  38. */
  39. public const VERSION = '5.0.0-beta.2';
  40. /**
  41. * Status starting.
  42. *
  43. * @var int
  44. */
  45. public const STATUS_STARTING = 1;
  46. /**
  47. * Status running.
  48. *
  49. * @var int
  50. */
  51. public const STATUS_RUNNING = 2;
  52. /**
  53. * Status shutdown.
  54. *
  55. * @var int
  56. */
  57. public const STATUS_SHUTDOWN = 4;
  58. /**
  59. * Status reloading.
  60. *
  61. * @var int
  62. */
  63. public const STATUS_RELOADING = 8;
  64. /**
  65. * Default backlog. Backlog is the maximum length of the queue of pending connections.
  66. *
  67. * @var int
  68. */
  69. public const DEFAULT_BACKLOG = 102400;
  70. /**
  71. * The safe distance for columns adjacent
  72. *
  73. * @var int
  74. */
  75. public const UI_SAFE_LENGTH = 4;
  76. /**
  77. * Worker id.
  78. *
  79. * @var int
  80. */
  81. public int $id = 0;
  82. /**
  83. * Name of the worker processes.
  84. *
  85. * @var string
  86. */
  87. public string $name = 'none';
  88. /**
  89. * Number of worker processes.
  90. *
  91. * @var int
  92. */
  93. public int $count = 1;
  94. /**
  95. * Unix user of processes, needs appropriate privileges (usually root).
  96. *
  97. * @var string
  98. */
  99. public string $user = '';
  100. /**
  101. * Unix group of processes, needs appropriate privileges (usually root).
  102. *
  103. * @var string
  104. */
  105. public string $group = '';
  106. /**
  107. * reloadable.
  108. *
  109. * @var bool
  110. */
  111. public bool $reloadable = true;
  112. /**
  113. * reuse port.
  114. *
  115. * @var bool
  116. */
  117. public bool $reusePort = false;
  118. /**
  119. * Emitted when worker processes start.
  120. *
  121. * @var ?callable
  122. */
  123. public $onWorkerStart = null;
  124. /**
  125. * Emitted when a socket connection is successfully established.
  126. *
  127. * @var ?callable
  128. */
  129. public $onConnect = null;
  130. /**
  131. * Emitted when websocket handshake completed (Only work when protocol is ws).
  132. *
  133. * @var ?callable
  134. */
  135. public $onWebSocketConnect = null;
  136. /**
  137. * Emitted when data is received.
  138. *
  139. * @var callable
  140. */
  141. public $onMessage = null;
  142. /**
  143. * Emitted when the other end of the socket sends a FIN packet.
  144. *
  145. * @var ?callable
  146. */
  147. public $onClose = null;
  148. /**
  149. * Emitted when an error occurs with connection.
  150. *
  151. * @var ?callable
  152. */
  153. public $onError = null;
  154. /**
  155. * Emitted when the send buffer becomes full.
  156. *
  157. * @var ?callable
  158. */
  159. public $onBufferFull = null;
  160. /**
  161. * Emitted when the send buffer becomes empty.
  162. *
  163. * @var ?callable
  164. */
  165. public $onBufferDrain = null;
  166. /**
  167. * Emitted when worker processes stopped.
  168. *
  169. * @var ?callable
  170. */
  171. public $onWorkerStop = null;
  172. /**
  173. * Emitted when worker processes get reload signal.
  174. *
  175. * @var ?callable
  176. */
  177. public $onWorkerReload = null;
  178. /**
  179. * Transport layer protocol.
  180. *
  181. * @var string
  182. */
  183. public string $transport = 'tcp';
  184. /**
  185. * Store all connections of clients.
  186. *
  187. * @var array
  188. */
  189. public array $connections = [];
  190. /**
  191. * Application layer protocol.
  192. *
  193. * @var ?string
  194. */
  195. public ?string $protocol = null;
  196. /**
  197. * Pause accept new connections or not.
  198. *
  199. * @var bool
  200. */
  201. protected bool $pauseAccept = true;
  202. /**
  203. * Is worker stopping ?
  204. * @var bool
  205. */
  206. public bool $stopping = false;
  207. /**
  208. * Daemonize.
  209. *
  210. * @var bool
  211. */
  212. public static bool $daemonize = false;
  213. /**
  214. * Stdout file.
  215. *
  216. * @var string
  217. */
  218. public static string $stdoutFile = '/dev/null';
  219. /**
  220. * The file to store master process PID.
  221. *
  222. * @var string
  223. */
  224. public static string $pidFile = '';
  225. /**
  226. * The file used to store the master process status file.
  227. *
  228. * @var string
  229. */
  230. public static string $statusFile = '';
  231. /**
  232. * Log file.
  233. *
  234. * @var mixed
  235. */
  236. public static mixed $logFile = '';
  237. /**
  238. * Global event loop.
  239. *
  240. * @var ?EventInterface
  241. */
  242. public static ?EventInterface $globalEvent = null;
  243. /**
  244. * Emitted when the master process get reload signal.
  245. *
  246. * @var ?callable
  247. */
  248. public static $onMasterReload = null;
  249. /**
  250. * Emitted when the master process terminated.
  251. *
  252. * @var ?callable
  253. */
  254. public static $onMasterStop = null;
  255. /**
  256. * Emitted when worker processes exited.
  257. *
  258. * @var ?callable
  259. */
  260. public static $onWorkerExit = null;
  261. /**
  262. * EventLoopClass
  263. *
  264. * @var class-string
  265. */
  266. public static string $eventLoopClass = '';
  267. /**
  268. * Process title
  269. *
  270. * @var string
  271. */
  272. public static string $processTitle = 'WorkerMan';
  273. /**
  274. * After sending the stop command to the child process stopTimeout seconds,
  275. * if the process is still living then forced to kill.
  276. *
  277. * @var int
  278. */
  279. public static int $stopTimeout = 2;
  280. /**
  281. * Command
  282. * @var string
  283. */
  284. public static string $command = '';
  285. /**
  286. * The PID of master process.
  287. *
  288. * @var int
  289. */
  290. protected static int $masterPid = 0;
  291. /**
  292. * Listening socket.
  293. *
  294. * @var resource
  295. */
  296. protected $mainSocket = null;
  297. /**
  298. * Socket name. The format is like this http://0.0.0.0:80 .
  299. *
  300. * @var string
  301. */
  302. protected string $socketName = '';
  303. /**
  304. * parse from socketName avoid parse again in master or worker
  305. * LocalSocket The format is like tcp://0.0.0.0:8080
  306. * @var ?string
  307. */
  308. protected ?string $localSocket = null;
  309. /**
  310. * Context of socket.
  311. *
  312. * @var resource
  313. */
  314. protected $socketContext = null;
  315. /**
  316. * @var stdClass
  317. */
  318. protected stdClass $context;
  319. /**
  320. * All worker instances.
  321. *
  322. * @var Worker[]
  323. */
  324. protected static array $workers = [];
  325. /**
  326. * All worker processes pid.
  327. * The format is like this [worker_id=>[pid=>pid, pid=>pid, ..], ..]
  328. *
  329. * @var array
  330. */
  331. protected static array $pidMap = [];
  332. /**
  333. * All worker processes waiting for restart.
  334. * The format is like this [pid=>pid, pid=>pid].
  335. *
  336. * @var array
  337. */
  338. protected static array $pidsToRestart = [];
  339. /**
  340. * Mapping from PID to worker process ID.
  341. * The format is like this [worker_id=>[0=>$pid, 1=>$pid, ..], ..].
  342. *
  343. * @var array
  344. */
  345. protected static array $idMap = [];
  346. /**
  347. * Current status.
  348. *
  349. * @var int
  350. */
  351. protected static int $status = self::STATUS_STARTING;
  352. /**
  353. * Maximum length of the worker names.
  354. *
  355. * @var int
  356. */
  357. protected static int $maxWorkerNameLength = 12;
  358. /**
  359. * Maximum length of the socket names.
  360. *
  361. * @var int
  362. */
  363. protected static int $maxSocketNameLength = 12;
  364. /**
  365. * Maximum length of the process user names.
  366. *
  367. * @var int
  368. */
  369. protected static int $maxUserNameLength = 12;
  370. /**
  371. * Maximum length of the Proto names.
  372. *
  373. * @var int
  374. */
  375. protected static int $maxProtoNameLength = 4;
  376. /**
  377. * Maximum length of the Processes names.
  378. *
  379. * @var int
  380. */
  381. protected static int $maxProcessesNameLength = 9;
  382. /**
  383. * Maximum length of the state names.
  384. *
  385. * @var int
  386. */
  387. protected static int $maxStateNameLength = 1;
  388. /**
  389. * The file to store status info of current worker process.
  390. *
  391. * @var string
  392. */
  393. protected static string $statisticsFile = '';
  394. /**
  395. * Start file.
  396. *
  397. * @var string
  398. */
  399. protected static string $startFile = '';
  400. /**
  401. * Processes for windows.
  402. *
  403. * @var array
  404. */
  405. protected static array $processForWindows = [];
  406. /**
  407. * Status info of current worker process.
  408. *
  409. * @var array
  410. */
  411. protected static array $globalStatistics = [
  412. 'start_timestamp' => 0,
  413. 'worker_exit_info' => []
  414. ];
  415. /**
  416. * Available event loops.
  417. *
  418. * @var array<string, string>
  419. */
  420. protected static array $availableEventLoops = [
  421. 'event' => Event::class,
  422. ];
  423. /**
  424. * PHP built-in protocols.
  425. *
  426. * @var array<string,string>
  427. */
  428. public const BUILD_IN_TRANSPORTS = [
  429. 'tcp' => 'tcp',
  430. 'udp' => 'udp',
  431. 'unix' => 'unix',
  432. 'ssl' => 'tcp'
  433. ];
  434. /**
  435. * PHP built-in error types.
  436. *
  437. * @var array<int,string>
  438. */
  439. public const ERROR_TYPE = [
  440. \E_ERROR => 'E_ERROR', // 1
  441. \E_WARNING => 'E_WARNING', // 2
  442. \E_PARSE => 'E_PARSE', // 4
  443. \E_NOTICE => 'E_NOTICE', // 8
  444. \E_CORE_ERROR => 'E_CORE_ERROR', // 16
  445. \E_CORE_WARNING => 'E_CORE_WARNING', // 32
  446. \E_COMPILE_ERROR => 'E_COMPILE_ERROR', // 64
  447. \E_COMPILE_WARNING => 'E_COMPILE_WARNING', // 128
  448. \E_USER_ERROR => 'E_USER_ERROR', // 256
  449. \E_USER_WARNING => 'E_USER_WARNING', // 512
  450. \E_USER_NOTICE => 'E_USER_NOTICE', // 1024
  451. \E_STRICT => 'E_STRICT', // 2048
  452. \E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', // 4096
  453. \E_DEPRECATED => 'E_DEPRECATED', // 8192
  454. \E_USER_DEPRECATED => 'E_USER_DEPRECATED' // 16384
  455. ];
  456. /**
  457. * Graceful stop or not.
  458. *
  459. * @var bool
  460. */
  461. protected static bool $gracefulStop = false;
  462. /**
  463. * Standard output stream
  464. * @var resource
  465. */
  466. protected static $outputStream = null;
  467. /**
  468. * If $outputStream support decorated
  469. * @var bool
  470. */
  471. protected static ?bool $outputDecorated = null;
  472. /**
  473. * Worker object's hash id(unique identifier).
  474. *
  475. * @var ?string
  476. */
  477. protected ?string $workerId = null;
  478. /**
  479. * Run all worker instances.
  480. *
  481. * @return void
  482. * @throws Exception
  483. */
  484. public static function runAll(): void
  485. {
  486. static::checkSapiEnv();
  487. static::init();
  488. static::parseCommand();
  489. static::lock();
  490. static::daemonize();
  491. static::initWorkers();
  492. static::installSignal();
  493. static::saveMasterPid();
  494. static::lock(\LOCK_UN);
  495. static::displayUI();
  496. static::forkWorkers();
  497. static::resetStd();
  498. static::monitorWorkers();
  499. }
  500. /**
  501. * Check sapi.
  502. *
  503. * @return void
  504. */
  505. protected static function checkSapiEnv(): void
  506. {
  507. // Only for cli.
  508. if (\PHP_SAPI !== 'cli') {
  509. exit("Only run in command line mode \n");
  510. }
  511. }
  512. /**
  513. * Init.
  514. *
  515. * @return void
  516. */
  517. protected static function init(): void
  518. {
  519. \set_error_handler(function ($code, $msg, $file, $line) {
  520. static::safeEcho("$msg in file $file on line $line\n");
  521. });
  522. // Start file.
  523. $backtrace = \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  524. static::$startFile = end($backtrace)['file'];
  525. $uniquePrefix = \str_replace('/', '_', static::$startFile);
  526. // Pid file.
  527. if (empty(static::$pidFile)) {
  528. static::$pidFile = __DIR__ . "/../$uniquePrefix.pid";
  529. }
  530. // Log file.
  531. if (empty(static::$logFile)) {
  532. static::$logFile = __DIR__ . '/../../workerman.log';
  533. }
  534. if (!\is_file(static::$logFile)) {
  535. // if /runtime/logs default folder not exists
  536. if (!is_dir(dirname(static::$logFile))) {
  537. @mkdir(dirname(static::$logFile), 0777, true);
  538. }
  539. \touch(static::$logFile);
  540. \chmod(static::$logFile, 0622);
  541. }
  542. // State.
  543. static::$status = static::STATUS_STARTING;
  544. // For statistics.
  545. static::$globalStatistics['start_timestamp'] = \time();
  546. // Process title.
  547. static::setProcessTitle(static::$processTitle . ': master process start_file=' . static::$startFile);
  548. // Init data for worker id.
  549. static::initId();
  550. // Timer init.
  551. Timer::init();
  552. }
  553. /**
  554. * Lock.
  555. *
  556. * @param int $flag
  557. * @return void
  558. */
  559. protected static function lock($flag = \LOCK_EX): void
  560. {
  561. static $fd;
  562. if (\DIRECTORY_SEPARATOR !== '/') {
  563. return;
  564. }
  565. $lockFile = static::$pidFile . '.lock';
  566. $fd = $fd ?: \fopen($lockFile, 'a+');
  567. if ($fd) {
  568. flock($fd, $flag);
  569. if ($flag === \LOCK_UN) {
  570. fclose($fd);
  571. $fd = null;
  572. clearstatcache();
  573. if (\is_file($lockFile)) {
  574. unlink($lockFile);
  575. }
  576. }
  577. }
  578. }
  579. /**
  580. * Init All worker instances.
  581. *
  582. * @return void
  583. * @throws Exception
  584. */
  585. protected static function initWorkers(): void
  586. {
  587. if (\DIRECTORY_SEPARATOR !== '/') {
  588. return;
  589. }
  590. static::$statisticsFile = static::$statusFile ?: __DIR__ . '/../workerman-' . posix_getpid() . '.status';
  591. foreach (static::$workers as $worker) {
  592. // Worker name.
  593. if (empty($worker->name)) {
  594. $worker->name = 'none';
  595. }
  596. // Get unix user of the worker process.
  597. if (empty($worker->user)) {
  598. $worker->user = static::getCurrentUser();
  599. } else {
  600. if (\posix_getuid() !== 0 && $worker->user !== static::getCurrentUser()) {
  601. static::log('Warning: You must have the root privileges to change uid and gid.');
  602. }
  603. }
  604. // Socket name.
  605. $worker->context->statusSocket = $worker->getSocketName();
  606. // Status name.
  607. $worker->context->statusState = '<g> [OK] </g>';
  608. // Get column mapping for UI
  609. foreach (static::getUiColumns() as $columnName => $prop) {
  610. !isset($worker->$prop) && !isset($worker->context->$prop) && $worker->context->$prop = 'NNNN';
  611. $propLength = \strlen((string)($worker->$prop ?? $worker->context->$prop));
  612. $key = 'max' . \ucfirst(\strtolower($columnName)) . 'NameLength';
  613. static::$$key = \max(static::$$key, $propLength);
  614. }
  615. // Listen.
  616. if (!$worker->reusePort) {
  617. $worker->listen();
  618. }
  619. }
  620. }
  621. /**
  622. * Get all worker instances.
  623. *
  624. * @return Worker[]
  625. */
  626. public static function getAllWorkers(): array
  627. {
  628. return static::$workers;
  629. }
  630. /**
  631. * Get global event-loop instance.
  632. *
  633. * @return EventInterface
  634. */
  635. public static function getEventLoop(): EventInterface
  636. {
  637. return static::$globalEvent;
  638. }
  639. /**
  640. * Get main socket resource
  641. * @return resource
  642. */
  643. public function getMainSocket()
  644. {
  645. return $this->mainSocket;
  646. }
  647. /**
  648. * Init idMap.
  649. *
  650. * @return void
  651. */
  652. protected static function initId(): void
  653. {
  654. foreach (static::$workers as $workerId => $worker) {
  655. $newIdMap = [];
  656. $worker->count = max($worker->count, 1);
  657. for ($key = 0; $key < $worker->count; $key++) {
  658. $newIdMap[$key] = static::$idMap[$workerId][$key] ?? 0;
  659. }
  660. static::$idMap[$workerId] = $newIdMap;
  661. }
  662. }
  663. /**
  664. * Get unix user of current porcess.
  665. *
  666. * @return string
  667. */
  668. protected static function getCurrentUser(): string
  669. {
  670. $userInfo = \posix_getpwuid(\posix_getuid());
  671. return $userInfo['name'];
  672. }
  673. /**
  674. * Display staring UI.
  675. *
  676. * @return void
  677. */
  678. protected static function displayUI(): void
  679. {
  680. $tmpArgv = static::getArgv();
  681. if (\in_array('-q', $tmpArgv)) {
  682. return;
  683. }
  684. if (\DIRECTORY_SEPARATOR !== '/') {
  685. static::safeEcho("----------------------- WORKERMAN -----------------------------\r\n");
  686. static::safeEcho('Workerman version:' . static::VERSION . ' PHP version:' . \PHP_VERSION . "\r\n");
  687. static::safeEcho("------------------------ WORKERS -------------------------------\r\n");
  688. static::safeEcho("worker listen processes status\r\n");
  689. return;
  690. }
  691. //show version
  692. $lineVersion = 'Workerman version:' . static::VERSION . \str_pad('PHP version:', 16, ' ', \STR_PAD_LEFT) . \PHP_VERSION . \str_pad('Event-loop:', 16, ' ', \STR_PAD_LEFT) . static::getEventLoopName() . \PHP_EOL;
  693. !\defined('LINE_VERSIOIN_LENGTH') && \define('LINE_VERSIOIN_LENGTH', \strlen($lineVersion));
  694. $totalLength = static::getSingleLineTotalLength();
  695. $lineOne = '<n>' . \str_pad('<w> WORKERMAN </w>', $totalLength + \strlen('<w></w>'), '-', \STR_PAD_BOTH) . '</n>' . \PHP_EOL;
  696. $lineTwo = \str_pad('<w> WORKERS </w>', $totalLength + \strlen('<w></w>'), '-', \STR_PAD_BOTH) . \PHP_EOL;
  697. static::safeEcho($lineOne . $lineVersion . $lineTwo);
  698. //Show title
  699. $title = '';
  700. foreach (static::getUiColumns() as $columnName => $prop) {
  701. $key = 'max' . \ucfirst(\strtolower($columnName)) . 'NameLength';
  702. //just keep compatible with listen name
  703. $columnName === 'socket' && $columnName = 'listen';
  704. $title .= "<w>{$columnName}</w>" . \str_pad('', static::$$key + static::UI_SAFE_LENGTH - \strlen($columnName));
  705. }
  706. $title && static::safeEcho($title . \PHP_EOL);
  707. //Show content
  708. foreach (static::$workers as $worker) {
  709. $content = '';
  710. foreach (static::getUiColumns() as $columnName => $prop) {
  711. $propValue = (string)($worker->$prop ?? $worker->context->$prop);
  712. $key = 'max' . \ucfirst(\strtolower($columnName)) . 'NameLength';
  713. \preg_match_all("/(<n>|<\/n>|<w>|<\/w>|<g>|<\/g>)/is", $propValue, $matches);
  714. $placeHolderLength = !empty($matches) ? \strlen(\implode('', $matches[0])) : 0;
  715. $content .= \str_pad($propValue, static::$$key + static::UI_SAFE_LENGTH + $placeHolderLength);
  716. }
  717. $content && static::safeEcho($content . \PHP_EOL);
  718. }
  719. //Show last line
  720. $lineLast = \str_pad('', static::getSingleLineTotalLength(), '-') . \PHP_EOL;
  721. !empty($content) && static::safeEcho($lineLast);
  722. if (static::$daemonize) {
  723. global $argv;
  724. $startFile = $argv[0];
  725. static::safeEcho('Input "php ' . $startFile . ' stop" to stop. Start success.' . "\n\n");
  726. } else {
  727. static::safeEcho("Press Ctrl+C to stop. Start success.\n");
  728. }
  729. }
  730. /**
  731. * Get UI columns to be shown in terminal
  732. *
  733. * 1. $columnMap: ['ui_column_name' => 'clas_property_name']
  734. * 2. Consider move into configuration in future
  735. *
  736. * @return array
  737. */
  738. public static function getUiColumns(): array
  739. {
  740. return [
  741. 'proto' => 'transport',
  742. 'user' => 'user',
  743. 'worker' => 'name',
  744. 'socket' => 'statusSocket',
  745. 'processes' => 'count',
  746. 'state' => 'statusState',
  747. ];
  748. }
  749. /**
  750. * Get single line total length for ui
  751. *
  752. * @return int
  753. */
  754. public static function getSingleLineTotalLength(): int
  755. {
  756. $totalLength = 0;
  757. foreach (static::getUiColumns() as $columnName => $prop) {
  758. $key = 'max' . \ucfirst(\strtolower($columnName)) . 'NameLength';
  759. $totalLength += static::$$key + static::UI_SAFE_LENGTH;
  760. }
  761. //Keep beauty when show less columns
  762. !\defined('LINE_VERSIOIN_LENGTH') && \define('LINE_VERSIOIN_LENGTH', 0);
  763. $totalLength <= LINE_VERSIOIN_LENGTH && $totalLength = LINE_VERSIOIN_LENGTH;
  764. return $totalLength;
  765. }
  766. /**
  767. * Parse command.
  768. *
  769. * @return void
  770. */
  771. protected static function parseCommand(): void
  772. {
  773. if (\DIRECTORY_SEPARATOR !== '/') {
  774. return;
  775. }
  776. global $argv;
  777. // Check argv;
  778. $startFile = $argv[0];
  779. $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";
  780. $availableCommands = [
  781. 'start',
  782. 'stop',
  783. 'restart',
  784. 'reload',
  785. 'status',
  786. 'connections',
  787. ];
  788. $availableMode = [
  789. '-d',
  790. '-g'
  791. ];
  792. $command = $mode = '';
  793. foreach (static::getArgv() as $value) {
  794. if (\in_array($value, $availableCommands)) {
  795. $command = $value;
  796. } elseif (\in_array($value, $availableMode)) {
  797. $mode = $value;
  798. }
  799. }
  800. if (!$command) {
  801. exit($usage);
  802. }
  803. // Start command.
  804. $modeStr = '';
  805. if ($command === 'start') {
  806. if ($mode === '-d' || static::$daemonize) {
  807. $modeStr = 'in DAEMON mode';
  808. } else {
  809. $modeStr = 'in DEBUG mode';
  810. }
  811. }
  812. static::log("Workerman[$startFile] $command $modeStr");
  813. // Get master process PID.
  814. $masterPid = \is_file(static::$pidFile) ? (int)\file_get_contents(static::$pidFile) : 0;
  815. // Master is still alive?
  816. if (static::checkMasterIsAlive($masterPid)) {
  817. if ($command === 'start') {
  818. static::log("Workerman[$startFile] already running");
  819. exit;
  820. }
  821. } elseif ($command !== 'start' && $command !== 'restart') {
  822. static::log("Workerman[$startFile] not run");
  823. exit;
  824. }
  825. $statisticsFile = static::$statusFile ?: __DIR__ . "/../workerman-$masterPid.status";
  826. // execute command.
  827. switch ($command) {
  828. case 'start':
  829. if ($mode === '-d') {
  830. static::$daemonize = true;
  831. }
  832. break;
  833. case 'status':
  834. while (1) {
  835. if (\is_file($statisticsFile)) {
  836. @\unlink($statisticsFile);
  837. }
  838. // Master process will send SIGIOT signal to all child processes.
  839. \posix_kill($masterPid, SIGIOT);
  840. // Sleep 1 second.
  841. \sleep(1);
  842. // Clear terminal.
  843. if ($mode === '-d') {
  844. static::safeEcho("\33[H\33[2J\33(B\33[m", true);
  845. }
  846. // Echo status data.
  847. static::safeEcho(static::formatStatusData($statisticsFile));
  848. if ($mode !== '-d') {
  849. @\unlink($statisticsFile);
  850. exit(0);
  851. }
  852. static::safeEcho("\nPress Ctrl+C to quit.\n\n");
  853. }
  854. case 'connections':
  855. if (\is_file($statisticsFile) && \is_writable($statisticsFile)) {
  856. \unlink($statisticsFile);
  857. }
  858. // Master process will send SIGIO signal to all child processes.
  859. \posix_kill($masterPid, SIGIO);
  860. // Waiting amoment.
  861. \usleep(500000);
  862. // Display statisitcs data from a disk file.
  863. if (\is_readable($statisticsFile)) {
  864. \readfile($statisticsFile);
  865. }
  866. exit(0);
  867. case 'restart':
  868. case 'stop':
  869. if ($mode === '-g') {
  870. static::$gracefulStop = true;
  871. $sig = \SIGQUIT;
  872. static::log("Workerman[$startFile] is gracefully stopping ...");
  873. } else {
  874. static::$gracefulStop = false;
  875. $sig = \SIGINT;
  876. static::log("Workerman[$startFile] is stopping ...");
  877. }
  878. // Send stop signal to master process.
  879. $masterPid && \posix_kill($masterPid, $sig);
  880. // Timeout.
  881. $timeout = static::$stopTimeout + 3;
  882. $startTime = \time();
  883. // Check master process is still alive?
  884. while (1) {
  885. $masterIsAlive = $masterPid && \posix_kill($masterPid, 0);
  886. if ($masterIsAlive) {
  887. // Timeout?
  888. if (!static::$gracefulStop && \time() - $startTime >= $timeout) {
  889. static::log("Workerman[$startFile] stop fail");
  890. exit;
  891. }
  892. // Waiting amoment.
  893. \usleep(10000);
  894. continue;
  895. }
  896. // Stop success.
  897. static::log("Workerman[$startFile] stop success");
  898. if ($command === 'stop') {
  899. exit(0);
  900. }
  901. if ($mode === '-d') {
  902. static::$daemonize = true;
  903. }
  904. break;
  905. }
  906. break;
  907. case 'reload':
  908. if ($mode === '-g') {
  909. $sig = \SIGUSR2;
  910. } else {
  911. $sig = \SIGUSR1;
  912. }
  913. \posix_kill($masterPid, $sig);
  914. exit;
  915. default :
  916. static::safeEcho('Unknown command: ' . $command . "\n");
  917. exit($usage);
  918. }
  919. }
  920. /**
  921. * Get argv.
  922. *
  923. * @return mixed
  924. */
  925. public static function getArgv(): mixed
  926. {
  927. global $argv;
  928. return isset($argv[1]) ? $argv : (static::$command ? \explode(' ', static::$command) : $argv);
  929. }
  930. /**
  931. * Format status data.
  932. *
  933. * @param $statisticsFile
  934. * @return string
  935. */
  936. protected static function formatStatusData($statisticsFile): string
  937. {
  938. static $totalRequestCache = [];
  939. if (!\is_readable($statisticsFile)) {
  940. return '';
  941. }
  942. $info = \file($statisticsFile, \FILE_IGNORE_NEW_LINES);
  943. if (!$info) {
  944. return '';
  945. }
  946. $statusStr = '';
  947. $currentTotalRequest = [];
  948. $workerInfo = \unserialize($info[0]);
  949. \ksort($workerInfo, SORT_NUMERIC);
  950. unset($info[0]);
  951. $dataWaitingSort = [];
  952. $readProcessStatus = false;
  953. $totalRequests = 0;
  954. $totalQps = 0;
  955. $totalConnections = 0;
  956. $totalFails = 0;
  957. $totalMemory = 0;
  958. $totalTimers = 0;
  959. $maxLen1 = static::$maxSocketNameLength;
  960. $maxLen2 = static::$maxWorkerNameLength;
  961. foreach ($info as $value) {
  962. if (!$readProcessStatus) {
  963. $statusStr .= $value . "\n";
  964. if (\preg_match('/^pid.*?memory.*?listening/', $value)) {
  965. $readProcessStatus = true;
  966. }
  967. continue;
  968. }
  969. if (\preg_match('/^[0-9]+/', $value, $pidMath)) {
  970. $pid = $pidMath[0];
  971. $dataWaitingSort[$pid] = $value;
  972. if (\preg_match('/^\S+?\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?/', $value, $match)) {
  973. $totalMemory += (int)\str_ireplace('M', '', $match[1]);
  974. $maxLen1 = \max($maxLen1, \strlen($match[2]));
  975. $maxLen2 = \max($maxLen2, \strlen($match[3]));
  976. $totalConnections += (int)$match[4];
  977. $totalFails += (int)$match[5];
  978. $totalTimers += (int)$match[6];
  979. $currentTotalRequest[$pid] = $match[7];
  980. $totalRequests += (int)$match[7];
  981. }
  982. }
  983. }
  984. foreach ($workerInfo as $pid => $info) {
  985. if (!isset($dataWaitingSort[$pid])) {
  986. $statusStr .= "$pid\t" . \str_pad('N/A', 7) . " "
  987. . \str_pad($info['listen'], static::$maxSocketNameLength) . " "
  988. . \str_pad((string)$info['name'], static::$maxWorkerNameLength) . " "
  989. . \str_pad('N/A', 11) . " " . \str_pad('N/A', 9) . " "
  990. . \str_pad('N/A', 7) . " " . \str_pad('N/A', 13) . " N/A [busy] \n";
  991. continue;
  992. }
  993. //$qps = isset($totalRequestCache[$pid]) ? $currentTotalRequest[$pid]
  994. if (!isset($totalRequestCache[$pid]) || !isset($currentTotalRequest[$pid])) {
  995. $qps = 0;
  996. } else {
  997. $qps = $currentTotalRequest[$pid] - $totalRequestCache[$pid];
  998. $totalQps += $qps;
  999. }
  1000. $statusStr .= $dataWaitingSort[$pid] . " " . \str_pad((string)$qps, 6) . " [idle]\n";
  1001. }
  1002. $totalRequestCache = $currentTotalRequest;
  1003. $statusStr .= "----------------------------------------------PROCESS STATUS---------------------------------------------------\n";
  1004. $statusStr .= "Summary\t" . \str_pad($totalMemory . 'M', 7) . " "
  1005. . \str_pad('-', $maxLen1) . " "
  1006. . \str_pad('-', $maxLen2) . " "
  1007. . \str_pad((string)$totalConnections, 11) . " " . \str_pad((string)$totalFails, 9) . " "
  1008. . \str_pad((string)$totalTimers, 7) . " " . \str_pad((string)$totalRequests, 13) . " "
  1009. . \str_pad((string)$totalQps, 6) . " [Summary] \n";
  1010. return $statusStr;
  1011. }
  1012. /**
  1013. * Install signal handler.
  1014. *
  1015. * @return void
  1016. */
  1017. protected static function installSignal(): void
  1018. {
  1019. if (\DIRECTORY_SEPARATOR !== '/') {
  1020. return;
  1021. }
  1022. $signals = [\SIGINT, \SIGTERM, \SIGHUP, \SIGTSTP, \SIGQUIT, \SIGUSR1, \SIGUSR2, \SIGIOT, \SIGIO];
  1023. foreach ($signals as $signal) {
  1024. \pcntl_signal($signal, [static::class, 'signalHandler'], false);
  1025. }
  1026. // ignore
  1027. \pcntl_signal(\SIGPIPE, \SIG_IGN, false);
  1028. }
  1029. /**
  1030. * Reinstall signal handler.
  1031. *
  1032. * @return void
  1033. */
  1034. protected static function reinstallSignal(): void
  1035. {
  1036. if (\DIRECTORY_SEPARATOR !== '/') {
  1037. return;
  1038. }
  1039. $signals = [\SIGINT, \SIGTERM, \SIGHUP, \SIGTSTP, \SIGQUIT, \SIGUSR1, \SIGUSR2, \SIGIOT, \SIGIO];
  1040. foreach ($signals as $signal) {
  1041. \pcntl_signal($signal, \SIG_IGN, false);
  1042. static::$globalEvent->onSignal($signal, [static::class, 'signalHandler']);
  1043. };
  1044. }
  1045. /**
  1046. * Signal handler.
  1047. *
  1048. * @param int $signal
  1049. * @throws Exception
  1050. */
  1051. public static function signalHandler(int $signal): void
  1052. {
  1053. switch ($signal) {
  1054. // Stop.
  1055. case \SIGINT:
  1056. case \SIGTERM:
  1057. case \SIGHUP:
  1058. case \SIGTSTP:
  1059. static::$gracefulStop = false;
  1060. static::stopAll();
  1061. break;
  1062. // Graceful stop.
  1063. case \SIGQUIT:
  1064. static::$gracefulStop = true;
  1065. static::stopAll();
  1066. break;
  1067. // Reload.
  1068. case \SIGUSR2:
  1069. case \SIGUSR1:
  1070. if (static::$status === static::STATUS_RELOADING || static::$status === static::STATUS_SHUTDOWN) {
  1071. return;
  1072. }
  1073. static::$gracefulStop = $signal === \SIGUSR2;
  1074. static::$pidsToRestart = static::getAllWorkerPids();
  1075. static::reload();
  1076. break;
  1077. // Show status.
  1078. case \SIGIOT:
  1079. static::writeStatisticsToStatusFile();
  1080. break;
  1081. // Show connection status.
  1082. case \SIGIO:
  1083. static::writeConnectionsStatisticsToStatusFile();
  1084. break;
  1085. }
  1086. }
  1087. /**
  1088. * Run as daemon mode.
  1089. *
  1090. * @throws Exception
  1091. */
  1092. protected static function daemonize(): void
  1093. {
  1094. if (!static::$daemonize || \DIRECTORY_SEPARATOR !== '/') {
  1095. return;
  1096. }
  1097. \umask(0);
  1098. $pid = \pcntl_fork();
  1099. if (-1 === $pid) {
  1100. throw new \RuntimeException('Fork fail');
  1101. } elseif ($pid > 0) {
  1102. exit(0);
  1103. }
  1104. if (-1 === \posix_setsid()) {
  1105. throw new \RuntimeException("Setsid fail");
  1106. }
  1107. // Fork again avoid SVR4 system regain the control of terminal.
  1108. $pid = \pcntl_fork();
  1109. if (-1 === $pid) {
  1110. throw new \RuntimeException("Fork fail");
  1111. } elseif (0 !== $pid) {
  1112. exit(0);
  1113. }
  1114. }
  1115. /**
  1116. * Redirect standard input and output.
  1117. *
  1118. * @param bool $throwException
  1119. * @return void
  1120. * @throws Exception
  1121. */
  1122. public static function resetStd(bool $throwException = true): void
  1123. {
  1124. if (!static::$daemonize || \DIRECTORY_SEPARATOR !== '/') {
  1125. return;
  1126. }
  1127. global $STDOUT, $STDERR;
  1128. $handle = \fopen(static::$stdoutFile, "a");
  1129. if ($handle) {
  1130. unset($handle);
  1131. \set_error_handler(function () {
  1132. });
  1133. if ($STDOUT) {
  1134. \fclose($STDOUT);
  1135. }
  1136. if ($STDERR) {
  1137. \fclose($STDERR);
  1138. }
  1139. if (\is_resource(\STDOUT)) {
  1140. \fclose(\STDOUT);
  1141. }
  1142. if (\is_resource(\STDERR)) {
  1143. \fclose(\STDERR);
  1144. }
  1145. $STDOUT = \fopen(static::$stdoutFile, "a");
  1146. $STDERR = \fopen(static::$stdoutFile, "a");
  1147. // Fix standard output cannot redirect of PHP 8.1.8's bug
  1148. if (\function_exists('posix_isatty') && \posix_isatty(2)) {
  1149. \ob_start(function ($string) {
  1150. \file_put_contents(static::$stdoutFile, $string, FILE_APPEND);
  1151. }, 1);
  1152. }
  1153. // change output stream
  1154. static::$outputStream = null;
  1155. static::outputStream($STDOUT);
  1156. \restore_error_handler();
  1157. return;
  1158. }
  1159. if ($throwException) {
  1160. throw new \RuntimeException('Can not open stdoutFile ' . static::$stdoutFile);
  1161. }
  1162. }
  1163. /**
  1164. * Save pid.
  1165. *
  1166. * @throws Exception
  1167. */
  1168. protected static function saveMasterPid(): void
  1169. {
  1170. if (\DIRECTORY_SEPARATOR !== '/') {
  1171. return;
  1172. }
  1173. static::$masterPid = \posix_getpid();
  1174. if (false === \file_put_contents(static::$pidFile, static::$masterPid)) {
  1175. throw new \RuntimeException('can not save pid to ' . static::$pidFile);
  1176. }
  1177. }
  1178. /**
  1179. * Get event loop name.
  1180. *
  1181. * @return string
  1182. */
  1183. protected static function getEventLoopName(): string
  1184. {
  1185. if (static::$eventLoopClass) {
  1186. return static::$eventLoopClass;
  1187. }
  1188. if (\class_exists(EventLoop::class)) {
  1189. static::$eventLoopClass = Revolt::class;
  1190. return static::$eventLoopClass;
  1191. }
  1192. $loopName = '';
  1193. foreach (static::$availableEventLoops as $name => $class) {
  1194. if (\extension_loaded($name)) {
  1195. $loopName = $name;
  1196. break;
  1197. }
  1198. }
  1199. if ($loopName) {
  1200. static::$eventLoopClass = static::$availableEventLoops[$loopName];
  1201. } else {
  1202. static::$eventLoopClass = Select::class;
  1203. }
  1204. return static::$eventLoopClass;
  1205. }
  1206. /**
  1207. * Get all pids of worker processes.
  1208. *
  1209. * @return array
  1210. */
  1211. protected static function getAllWorkerPids(): array
  1212. {
  1213. $pidArray = [];
  1214. foreach (static::$pidMap as $workerPidArray) {
  1215. foreach ($workerPidArray as $workerPid) {
  1216. $pidArray[$workerPid] = $workerPid;
  1217. }
  1218. }
  1219. return $pidArray;
  1220. }
  1221. /**
  1222. * Fork some worker processes.
  1223. *
  1224. * @return void
  1225. * @throws Exception
  1226. */
  1227. protected static function forkWorkers(): void
  1228. {
  1229. if (\DIRECTORY_SEPARATOR === '/') {
  1230. static::forkWorkersForLinux();
  1231. } else {
  1232. static::forkWorkersForWindows();
  1233. }
  1234. }
  1235. /**
  1236. * Fork some worker processes.
  1237. *
  1238. * @return void
  1239. * @throws Exception
  1240. */
  1241. protected static function forkWorkersForLinux(): void
  1242. {
  1243. foreach (static::$workers as $worker) {
  1244. if (static::$status === static::STATUS_STARTING) {
  1245. if (empty($worker->name)) {
  1246. $worker->name = $worker->getSocketName();
  1247. }
  1248. $workerNameLength = \strlen($worker->name);
  1249. if (static::$maxWorkerNameLength < $workerNameLength) {
  1250. static::$maxWorkerNameLength = $workerNameLength;
  1251. }
  1252. }
  1253. while (\count(static::$pidMap[$worker->workerId]) < $worker->count) {
  1254. static::forkOneWorkerForLinux($worker);
  1255. }
  1256. }
  1257. }
  1258. /**
  1259. * Fork some worker processes.
  1260. *
  1261. * @return void
  1262. * @throws Exception
  1263. */
  1264. protected static function forkWorkersForWindows(): void
  1265. {
  1266. $files = static::getStartFilesForWindows();
  1267. if (\in_array('-q', static::getArgv()) || \count($files) === 1) {
  1268. if (\count(static::$workers) > 1) {
  1269. static::safeEcho("@@@ Error: multi workers init in one php file are not support @@@\r\n");
  1270. static::safeEcho("@@@ See https://www.workerman.net/doc/workerman/faq/multi-woker-for-windows.html @@@\r\n");
  1271. } elseif (\count(static::$workers) <= 0) {
  1272. exit("@@@no worker inited@@@\r\n\r\n");
  1273. }
  1274. \reset(static::$workers);
  1275. /** @var Worker $worker */
  1276. $worker = current(static::$workers);
  1277. Timer::delAll();
  1278. //Update process state.
  1279. static::$status = static::STATUS_RUNNING;
  1280. // Register shutdown function for checking errors.
  1281. \register_shutdown_function([__CLASS__, 'checkErrors']);
  1282. // Create a global event loop.
  1283. if (!static::$globalEvent) {
  1284. $eventLoopClass = static::getEventLoopName();
  1285. static::$globalEvent = new $eventLoopClass;
  1286. static::$globalEvent->setErrorHandler(function ($exception) {
  1287. static::stopAll(250, $exception);
  1288. });
  1289. }
  1290. // Reinstall signal.
  1291. static::reinstallSignal();
  1292. // Init Timer.
  1293. Timer::init(static::$globalEvent);
  1294. \restore_error_handler();
  1295. // Display UI.
  1296. static::safeEcho(\str_pad($worker->name, 21) . \str_pad($worker->getSocketName(), 36) . \str_pad((string)$worker->count, 10) . "[ok]\n");
  1297. $worker->listen();
  1298. $worker->run();
  1299. static::$globalEvent->run();
  1300. if (static::$status !== self::STATUS_SHUTDOWN) {
  1301. $err = new Exception('event-loop exited');
  1302. static::log($err);
  1303. exit(250);
  1304. }
  1305. exit(0);
  1306. } else {
  1307. static::$globalEvent = new Select();
  1308. static::$globalEvent->setErrorHandler(function ($exception) {
  1309. static::stopAll(250, $exception);
  1310. });
  1311. Timer::init(static::$globalEvent);
  1312. foreach ($files as $startFile) {
  1313. static::forkOneWorkerForWindows($startFile);
  1314. }
  1315. }
  1316. }
  1317. /**
  1318. * Get start files for windows.
  1319. *
  1320. * @return array
  1321. */
  1322. public static function getStartFilesForWindows(): array
  1323. {
  1324. $files = [];
  1325. foreach (static::getArgv() as $file) {
  1326. if (\is_file($file)) {
  1327. $files[$file] = $file;
  1328. }
  1329. }
  1330. return $files;
  1331. }
  1332. /**
  1333. * Fork one worker process.
  1334. *
  1335. * @param string $startFile
  1336. */
  1337. public static function forkOneWorkerForWindows(string $startFile): void
  1338. {
  1339. $startFile = \realpath($startFile);
  1340. $descriptorspec = array(
  1341. STDIN, STDOUT, STDOUT
  1342. );
  1343. $pipes = array();
  1344. $process = \proc_open('"' . PHP_BINARY . '" ' . " \"$startFile\" -q", $descriptorspec, $pipes, null, null, ['bypass_shell' => true]);
  1345. if (empty(static::$globalEvent)) {
  1346. static::$globalEvent = new Select();
  1347. static::$globalEvent->setErrorHandler(function ($exception) {
  1348. static::stopAll(250, $exception);
  1349. });
  1350. Timer::init(static::$globalEvent);
  1351. }
  1352. // 保存子进程句柄
  1353. static::$processForWindows[$startFile] = array($process, $startFile);
  1354. }
  1355. /**
  1356. * check worker status for windows.
  1357. * @return void
  1358. */
  1359. public static function checkWorkerStatusForWindows(): void
  1360. {
  1361. foreach (static::$processForWindows as $processData) {
  1362. $process = $processData[0];
  1363. $startFile = $processData[1];
  1364. $status = \proc_get_status($process);
  1365. if (isset($status['running'])) {
  1366. if (!$status['running']) {
  1367. static::safeEcho("process $startFile terminated and try to restart\n");
  1368. \proc_close($process);
  1369. static::forkOneWorkerForWindows($startFile);
  1370. }
  1371. } else {
  1372. static::safeEcho("proc_get_status fail\n");
  1373. }
  1374. }
  1375. }
  1376. /**
  1377. * Fork one worker process.
  1378. *
  1379. * @param self $worker
  1380. * @throws Exception|Throwable
  1381. */
  1382. protected static function forkOneWorkerForLinux(self $worker): void
  1383. {
  1384. // Get available worker id.
  1385. $id = static::getId($worker->workerId, 0);
  1386. $pid = \pcntl_fork();
  1387. // For master process.
  1388. if ($pid > 0) {
  1389. static::$pidMap[$worker->workerId][$pid] = $pid;
  1390. static::$idMap[$worker->workerId][$id] = $pid;
  1391. } // For child processes.
  1392. elseif (0 === $pid) {
  1393. \srand();
  1394. \mt_srand();
  1395. static::$gracefulStop = false;
  1396. if (static::$status === static::STATUS_STARTING) {
  1397. static::resetStd();
  1398. }
  1399. static::$pidsToRestart = static::$pidMap = [];
  1400. // Remove other listener.
  1401. foreach (static::$workers as $key => $oneWorker) {
  1402. if ($oneWorker->workerId !== $worker->workerId) {
  1403. $oneWorker->unlisten();
  1404. unset(static::$workers[$key]);
  1405. }
  1406. }
  1407. Timer::delAll();
  1408. //Update process state.
  1409. static::$status = static::STATUS_RUNNING;
  1410. // Register shutdown function for checking errors.
  1411. \register_shutdown_function(["\\Workerman\\Worker", 'checkErrors']);
  1412. // Create a global event loop.
  1413. if (!static::$globalEvent) {
  1414. $eventLoopClass = static::getEventLoopName();
  1415. static::$globalEvent = new $eventLoopClass;
  1416. static::$globalEvent->setErrorHandler(function ($exception) {
  1417. static::stopAll(250, $exception);
  1418. });
  1419. }
  1420. // Reinstall signal.
  1421. static::reinstallSignal();
  1422. // Init Timer.
  1423. Timer::init(static::$globalEvent);
  1424. \restore_error_handler();
  1425. static::setProcessTitle(self::$processTitle . ': worker process ' . $worker->name . ' ' . $worker->getSocketName());
  1426. $worker->setUserAndGroup();
  1427. $worker->id = $id;
  1428. $worker->run();
  1429. // Main loop.
  1430. static::$globalEvent->run();
  1431. if (static::$status !== self::STATUS_SHUTDOWN) {
  1432. $err = new Exception('event-loop exited');
  1433. static::log($err);
  1434. exit(250);
  1435. }
  1436. exit(0);
  1437. } else {
  1438. throw new \RuntimeException("forkOneWorker fail");
  1439. }
  1440. }
  1441. /**
  1442. * Get worker id.
  1443. *
  1444. * @param string $workerId
  1445. * @param int $pid
  1446. *
  1447. * @return false|int|string
  1448. */
  1449. protected static function getId(string $workerId, int $pid): bool|int|string
  1450. {
  1451. return \array_search($pid, static::$idMap[$workerId]);
  1452. }
  1453. /**
  1454. * Set unix user and group for current process.
  1455. *
  1456. * @return void
  1457. */
  1458. public function setUserAndGroup(): void
  1459. {
  1460. // Get uid.
  1461. $userInfo = \posix_getpwnam($this->user);
  1462. if (!$userInfo) {
  1463. static::log("Warning: User {$this->user} not exists");
  1464. return;
  1465. }
  1466. $uid = $userInfo['uid'];
  1467. // Get gid.
  1468. if ($this->group) {
  1469. $groupInfo = \posix_getgrnam($this->group);
  1470. if (!$groupInfo) {
  1471. static::log("Warning: Group {$this->group} not exists");
  1472. return;
  1473. }
  1474. $gid = $groupInfo['gid'];
  1475. } else {
  1476. $gid = $userInfo['gid'];
  1477. }
  1478. // Set uid and gid.
  1479. if ($uid !== \posix_getuid() || $gid !== \posix_getgid()) {
  1480. if (!\posix_setgid($gid) || !\posix_initgroups($userInfo['name'], $gid) || !\posix_setuid($uid)) {
  1481. static::log("Warning: change gid or uid fail.");
  1482. }
  1483. }
  1484. }
  1485. /**
  1486. * Set process name.
  1487. *
  1488. * @param string $title
  1489. * @return void
  1490. */
  1491. protected static function setProcessTitle(string $title): void
  1492. {
  1493. \set_error_handler(function () {
  1494. });
  1495. \cli_set_process_title($title);
  1496. \restore_error_handler();
  1497. }
  1498. /**
  1499. * Monitor all child processes.
  1500. *
  1501. * @return void
  1502. * @throws Exception
  1503. */
  1504. protected static function monitorWorkers(): void
  1505. {
  1506. if (\DIRECTORY_SEPARATOR === '/') {
  1507. static::monitorWorkersForLinux();
  1508. } else {
  1509. static::monitorWorkersForWindows();
  1510. }
  1511. }
  1512. /**
  1513. * Monitor all child processes.
  1514. *
  1515. * @return void
  1516. * @throws Exception
  1517. */
  1518. protected static function monitorWorkersForLinux(): void
  1519. {
  1520. static::$status = static::STATUS_RUNNING;
  1521. while (1) {
  1522. // Calls signal handlers for pending signals.
  1523. \pcntl_signal_dispatch();
  1524. // Suspends execution of the current process until a child has exited, or until a signal is delivered
  1525. $status = 0;
  1526. $pid = \pcntl_wait($status, \WUNTRACED);
  1527. // Calls signal handlers for pending signals again.
  1528. \pcntl_signal_dispatch();
  1529. // If a child has already exited.
  1530. if ($pid > 0) {
  1531. // Find out which worker process exited.
  1532. foreach (static::$pidMap as $workerId => $workerPidArray) {
  1533. if (isset($workerPidArray[$pid])) {
  1534. $worker = static::$workers[$workerId];
  1535. // Fix exit with status 2 for php8.2
  1536. if ($status === \SIGINT && static::$status === static::STATUS_SHUTDOWN) {
  1537. $status = 0;
  1538. }
  1539. // Exit status.
  1540. if ($status !== 0) {
  1541. static::log("worker[{$worker->name}:$pid] exit with status $status");
  1542. }
  1543. // onWorkerExit
  1544. if (static::$onWorkerExit) {
  1545. try {
  1546. (static::$onWorkerExit)($worker, $status, $pid);
  1547. } catch (Throwable $exception) {
  1548. static::log("worker[{$worker->name}] onWorkerExit $exception");
  1549. }
  1550. }
  1551. // For Statistics.
  1552. if (!isset(static::$globalStatistics['worker_exit_info'][$workerId][$status])) {
  1553. static::$globalStatistics['worker_exit_info'][$workerId][$status] = 0;
  1554. }
  1555. ++static::$globalStatistics['worker_exit_info'][$workerId][$status];
  1556. // Clear process data.
  1557. unset(static::$pidMap[$workerId][$pid]);
  1558. // Mark id is available.
  1559. $id = static::getId($workerId, $pid);
  1560. static::$idMap[$workerId][$id] = 0;
  1561. break;
  1562. }
  1563. }
  1564. // Is still running state then fork a new worker process.
  1565. if (static::$status !== static::STATUS_SHUTDOWN) {
  1566. static::forkWorkers();
  1567. // If reloading continue.
  1568. if (isset(static::$pidsToRestart[$pid])) {
  1569. unset(static::$pidsToRestart[$pid]);
  1570. static::reload();
  1571. }
  1572. }
  1573. }
  1574. // If shutdown state and all child processes exited then master process exit.
  1575. if (static::$status === static::STATUS_SHUTDOWN && !static::getAllWorkerPids()) {
  1576. static::exitAndClearAll();
  1577. }
  1578. }
  1579. }
  1580. /**
  1581. * Monitor all child processes.
  1582. *
  1583. * @return void
  1584. */
  1585. protected static function monitorWorkersForWindows(): void
  1586. {
  1587. Timer::add(1, "\\Workerman\\Worker::checkWorkerStatusForWindows");
  1588. static::$globalEvent->run();
  1589. }
  1590. /**
  1591. * Exit current process.
  1592. */
  1593. protected static function exitAndClearAll()
  1594. {
  1595. foreach (static::$workers as $worker) {
  1596. $socketName = $worker->getSocketName();
  1597. if ($worker->transport === 'unix' && $socketName) {
  1598. list(, $address) = \explode(':', $socketName, 2);
  1599. $address = substr($address, strpos($address, '/') + 2);
  1600. @\unlink($address);
  1601. }
  1602. }
  1603. @\unlink(static::$pidFile);
  1604. static::log("Workerman[" . \basename(static::$startFile) . "] has been stopped");
  1605. if (static::$onMasterStop) {
  1606. \call_user_func(static::$onMasterStop);
  1607. }
  1608. exit(0);
  1609. }
  1610. /**
  1611. * Execute reload.
  1612. *
  1613. * @return void
  1614. * @throws Exception
  1615. */
  1616. protected static function reload(): void
  1617. {
  1618. // For master process.
  1619. if (static::$masterPid === \posix_getpid()) {
  1620. $sig = static::$gracefulStop ? \SIGUSR2 : \SIGUSR1;
  1621. // Set reloading state.
  1622. if (static::$status !== static::STATUS_RELOADING && static::$status !== static::STATUS_SHUTDOWN) {
  1623. static::log("Workerman[" . \basename(static::$startFile) . "] reloading");
  1624. static::$status = static::STATUS_RELOADING;
  1625. static::resetStd(false);
  1626. // Try to emit onMasterReload callback.
  1627. if (static::$onMasterReload) {
  1628. try {
  1629. \call_user_func(static::$onMasterReload);
  1630. } catch (Throwable $e) {
  1631. static::stopAll(250, $e);
  1632. }
  1633. static::initId();
  1634. }
  1635. // Send reload signal to all child processes.
  1636. $reloadablePidArray = [];
  1637. foreach (static::$pidMap as $workerId => $workerPidArray) {
  1638. $worker = static::$workers[$workerId];
  1639. if ($worker->reloadable) {
  1640. foreach ($workerPidArray as $pid) {
  1641. $reloadablePidArray[$pid] = $pid;
  1642. }
  1643. } else {
  1644. foreach ($workerPidArray as $pid) {
  1645. // Send reload signal to a worker process which reloadable is false.
  1646. \posix_kill($pid, $sig);
  1647. }
  1648. }
  1649. }
  1650. // Get all pids that are waiting reload.
  1651. static::$pidsToRestart = \array_intersect(static::$pidsToRestart, $reloadablePidArray);
  1652. }
  1653. // Reload complete.
  1654. if (empty(static::$pidsToRestart)) {
  1655. if (static::$status !== static::STATUS_SHUTDOWN) {
  1656. static::$status = static::STATUS_RUNNING;
  1657. }
  1658. return;
  1659. }
  1660. // Continue reload.
  1661. $oneWorkerPid = \current(static::$pidsToRestart);
  1662. // Send reload signal to a worker process.
  1663. \posix_kill($oneWorkerPid, $sig);
  1664. // If the process does not exit after stopTimeout seconds try to kill it.
  1665. if (!static::$gracefulStop) {
  1666. Timer::add(static::$stopTimeout, '\posix_kill', [$oneWorkerPid, \SIGKILL], false);
  1667. }
  1668. } // For child processes.
  1669. else {
  1670. \reset(static::$workers);
  1671. $worker = \current(static::$workers);
  1672. // Try to emit onWorkerReload callback.
  1673. if ($worker->onWorkerReload) {
  1674. try {
  1675. \call_user_func($worker->onWorkerReload, $worker);
  1676. } catch (Throwable $e) {
  1677. static::stopAll(250, $e);
  1678. }
  1679. }
  1680. if ($worker->reloadable) {
  1681. static::stopAll();
  1682. } else {
  1683. static::resetStd(false);
  1684. }
  1685. }
  1686. }
  1687. /**
  1688. * Stop all.
  1689. *
  1690. * @param int $code
  1691. * @param mixed $log
  1692. */
  1693. public static function stopAll(int $code = 0, mixed $log = ''): void
  1694. {
  1695. if ($log) {
  1696. static::log($log);
  1697. }
  1698. static::$status = static::STATUS_SHUTDOWN;
  1699. // For master process.
  1700. if (\DIRECTORY_SEPARATOR === '/' && static::$masterPid === \posix_getpid()) {
  1701. static::log("Workerman[" . \basename(static::$startFile) . "] stopping ...");
  1702. $workerPidArray = static::getAllWorkerPids();
  1703. // Send stop signal to all child processes.
  1704. $sig = static::$gracefulStop ? \SIGQUIT : \SIGINT;
  1705. foreach ($workerPidArray as $workerPid) {
  1706. // Fix exit with status 2 for php8.2
  1707. if ($sig === \SIGINT && !static::$daemonize) {
  1708. Timer::add(1, '\posix_kill', [$workerPid, \SIGINT], false);
  1709. } else {
  1710. \posix_kill($workerPid, $sig);
  1711. }
  1712. if (!static::$gracefulStop) {
  1713. Timer::add(ceil(static::$stopTimeout), '\posix_kill', [$workerPid, \SIGKILL], false);
  1714. }
  1715. }
  1716. Timer::add(1, "\\Workerman\\Worker::checkIfChildRunning");
  1717. // Remove statistics file.
  1718. if (\is_file(static::$statisticsFile)) {
  1719. @\unlink(static::$statisticsFile);
  1720. }
  1721. } // For child processes.
  1722. else {
  1723. // Execute exit.
  1724. $workers = array_reverse(static::$workers);
  1725. foreach ($workers as $worker) {
  1726. if (!$worker->stopping) {
  1727. $worker->stop();
  1728. $worker->stopping = true;
  1729. }
  1730. }
  1731. if (!static::$gracefulStop || ConnectionInterface::$statistics['connection_count'] <= 0) {
  1732. static::$workers = [];
  1733. if (static::$globalEvent) {
  1734. static::$globalEvent->stop();
  1735. }
  1736. try {
  1737. exit($code);
  1738. } catch (Exception $e) {
  1739. }
  1740. }
  1741. }
  1742. }
  1743. /**
  1744. * check if child processes is really running
  1745. */
  1746. public static function checkIfChildRunning(): void
  1747. {
  1748. foreach (static::$pidMap as $workerId => $workerPidArray) {
  1749. foreach ($workerPidArray as $pid => $workerPid) {
  1750. if (!\posix_kill($pid, 0)) {
  1751. unset(static::$pidMap[$workerId][$pid]);
  1752. }
  1753. }
  1754. }
  1755. }
  1756. /**
  1757. * Get process status.
  1758. *
  1759. * @return int
  1760. */
  1761. public static function getStatus(): int
  1762. {
  1763. return static::$status;
  1764. }
  1765. /**
  1766. * If stop gracefully.
  1767. *
  1768. * @return bool
  1769. */
  1770. public static function getGracefulStop(): bool
  1771. {
  1772. return static::$gracefulStop;
  1773. }
  1774. /**
  1775. * Write statistics data to disk.
  1776. *
  1777. * @return void
  1778. */
  1779. protected static function writeStatisticsToStatusFile(): void
  1780. {
  1781. // For master process.
  1782. if (static::$masterPid === \posix_getpid()) {
  1783. $allWorkerInfo = [];
  1784. foreach (static::$pidMap as $workerId => $pidArray) {
  1785. /** @var /Workerman/Worker $worker */
  1786. $worker = static::$workers[$workerId];
  1787. foreach ($pidArray as $pid) {
  1788. $allWorkerInfo[$pid] = ['name' => $worker->name, 'listen' => $worker->getSocketName()];
  1789. }
  1790. }
  1791. \file_put_contents(static::$statisticsFile, \serialize($allWorkerInfo) . "\n", \FILE_APPEND);
  1792. $loadavg = \function_exists('sys_getloadavg') ? \array_map('round', \sys_getloadavg(), [2, 2, 2]) : ['-', '-', '-'];
  1793. \file_put_contents(static::$statisticsFile,
  1794. "----------------------------------------------GLOBAL STATUS----------------------------------------------------\n", \FILE_APPEND);
  1795. \file_put_contents(static::$statisticsFile,
  1796. 'Workerman version:' . static::VERSION . " PHP version:" . \PHP_VERSION . "\n", \FILE_APPEND);
  1797. \file_put_contents(static::$statisticsFile, 'start time:' . \date('Y-m-d H:i:s',
  1798. 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",
  1799. FILE_APPEND);
  1800. $loadStr = 'load average: ' . \implode(", ", $loadavg);
  1801. \file_put_contents(static::$statisticsFile,
  1802. \str_pad($loadStr, 33) . 'event-loop:' . static::getEventLoopName() . "\n", \FILE_APPEND);
  1803. \file_put_contents(static::$statisticsFile,
  1804. \count(static::$pidMap) . ' workers ' . \count(static::getAllWorkerPids()) . " processes\n",
  1805. \FILE_APPEND);
  1806. \file_put_contents(static::$statisticsFile,
  1807. \str_pad('worker_name', static::$maxWorkerNameLength) . " exit_status exit_count\n", \FILE_APPEND);
  1808. foreach (static::$pidMap as $workerId => $workerPidArray) {
  1809. $worker = static::$workers[$workerId];
  1810. if (isset(static::$globalStatistics['worker_exit_info'][$workerId])) {
  1811. foreach (static::$globalStatistics['worker_exit_info'][$workerId] as $workerExitStatus => $workerExitCount) {
  1812. \file_put_contents(static::$statisticsFile,
  1813. \str_pad($worker->name, static::$maxWorkerNameLength) . " " . \str_pad((string)$workerExitStatus,
  1814. 16) . " $workerExitCount\n", \FILE_APPEND);
  1815. }
  1816. } else {
  1817. \file_put_contents(static::$statisticsFile,
  1818. \str_pad($worker->name, static::$maxWorkerNameLength) . " " . \str_pad('0', 16) . " 0\n",
  1819. \FILE_APPEND);
  1820. }
  1821. }
  1822. \file_put_contents(static::$statisticsFile,
  1823. "----------------------------------------------PROCESS STATUS---------------------------------------------------\n",
  1824. \FILE_APPEND);
  1825. \file_put_contents(static::$statisticsFile,
  1826. "pid\tmemory " . \str_pad('listening', static::$maxSocketNameLength) . " " . \str_pad('worker_name',
  1827. static::$maxWorkerNameLength) . " connections " . \str_pad('send_fail', 9) . " "
  1828. . \str_pad('timers', 8) . \str_pad('total_request', 13) . " qps status\n", \FILE_APPEND);
  1829. \chmod(static::$statisticsFile, 0722);
  1830. foreach (static::getAllWorkerPids() as $workerPid) {
  1831. \posix_kill($workerPid, \SIGIOT);
  1832. }
  1833. return;
  1834. }
  1835. // For child processes.
  1836. \gc_collect_cycles();
  1837. if (\function_exists('gc_mem_caches')) {
  1838. \gc_mem_caches();
  1839. }
  1840. \reset(static::$workers);
  1841. /** @var static $worker */
  1842. $worker = current(static::$workers);
  1843. $workerStatusStr = \posix_getpid() . "\t" . \str_pad((string)round(memory_get_usage() / (1024 * 1024), 2) . "M", 7)
  1844. . " " . \str_pad($worker->getSocketName(), static::$maxSocketNameLength) . " "
  1845. . \str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::$maxWorkerNameLength)
  1846. . " ";
  1847. $workerStatusStr .= \str_pad((string)ConnectionInterface::$statistics['connection_count'], 11)
  1848. . " " . \str_pad((string)ConnectionInterface::$statistics['send_fail'], 9)
  1849. . " " . \str_pad((string)static::$globalEvent->getTimerCount(), 7)
  1850. . " " . \str_pad((string)ConnectionInterface::$statistics['total_request'], 13) . "\n";
  1851. \file_put_contents(static::$statisticsFile, $workerStatusStr, \FILE_APPEND);
  1852. }
  1853. /**
  1854. * Write statistics data to disk.
  1855. *
  1856. * @return void
  1857. */
  1858. protected static function writeConnectionsStatisticsToStatusFile(): void
  1859. {
  1860. // For master process.
  1861. if (static::$masterPid === \posix_getpid()) {
  1862. \file_put_contents(static::$statisticsFile, "--------------------------------------------------------------------- WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", \FILE_APPEND);
  1863. \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);
  1864. \chmod(static::$statisticsFile, 0722);
  1865. foreach (static::getAllWorkerPids() as $workerPid) {
  1866. \posix_kill($workerPid, \SIGIO);
  1867. }
  1868. return;
  1869. }
  1870. // For child processes.
  1871. $bytesFormat = function ($bytes) {
  1872. if ($bytes > 1024 * 1024 * 1024 * 1024) {
  1873. return round($bytes / (1024 * 1024 * 1024 * 1024), 1) . "TB";
  1874. }
  1875. if ($bytes > 1024 * 1024 * 1024) {
  1876. return round($bytes / (1024 * 1024 * 1024), 1) . "GB";
  1877. }
  1878. if ($bytes > 1024 * 1024) {
  1879. return round($bytes / (1024 * 1024), 1) . "MB";
  1880. }
  1881. if ($bytes > 1024) {
  1882. return round($bytes / (1024), 1) . "KB";
  1883. }
  1884. return $bytes . "B";
  1885. };
  1886. $pid = \posix_getpid();
  1887. $str = '';
  1888. \reset(static::$workers);
  1889. $currentWorker = current(static::$workers);
  1890. $defaultWorkerName = $currentWorker->name;
  1891. /** @var static $worker */
  1892. foreach (TcpConnection::$connections as $connection) {
  1893. /** @var \Workerman\Connection\TcpConnection $connection */
  1894. $transport = $connection->transport;
  1895. $ipv4 = $connection->isIpV4() ? ' 1' : ' 0';
  1896. $ipv6 = $connection->isIpV6() ? ' 1' : ' 0';
  1897. $recvQ = $bytesFormat($connection->getRecvBufferQueueSize());
  1898. $sendQ = $bytesFormat($connection->getSendBufferQueueSize());
  1899. $localAddress = \trim($connection->getLocalAddress());
  1900. $remoteAddress = \trim($connection->getRemoteAddress());
  1901. $state = $connection->getStatus(false);
  1902. $bytesRead = $bytesFormat($connection->bytesRead);
  1903. $bytesWritten = $bytesFormat($connection->bytesWritten);
  1904. $id = $connection->id;
  1905. $protocol = $connection->protocol ? $connection->protocol : $connection->transport;
  1906. $pos = \strrpos($protocol, '\\');
  1907. if ($pos) {
  1908. $protocol = \substr($protocol, $pos + 1);
  1909. }
  1910. if (\strlen($protocol) > 15) {
  1911. $protocol = \substr($protocol, 0, 13) . '..';
  1912. }
  1913. $workerName = isset($connection->worker) ? $connection->worker->name : $defaultWorkerName;
  1914. if (\strlen($workerName) > 14) {
  1915. $workerName = \substr($workerName, 0, 12) . '..';
  1916. }
  1917. $str .= \str_pad((string)$pid, 9) . \str_pad($workerName, 16) . \str_pad((string)$id, 10) . \str_pad($transport, 8)
  1918. . \str_pad($protocol, 16) . \str_pad($ipv4, 7) . \str_pad($ipv6, 7) . \str_pad($recvQ, 13)
  1919. . \str_pad($sendQ, 13) . \str_pad($bytesRead, 13) . \str_pad($bytesWritten, 13) . ' '
  1920. . \str_pad($state, 14) . ' ' . \str_pad($localAddress, 22) . ' ' . \str_pad($remoteAddress, 22) . "\n";
  1921. }
  1922. if ($str) {
  1923. \file_put_contents(static::$statisticsFile, $str, \FILE_APPEND);
  1924. }
  1925. }
  1926. /**
  1927. * Check errors when current process exited.
  1928. *
  1929. * @return void
  1930. */
  1931. public static function checkErrors(): void
  1932. {
  1933. if (static::STATUS_SHUTDOWN !== static::$status) {
  1934. $errorMsg = \DIRECTORY_SEPARATOR === '/' ? 'Worker[' . \posix_getpid() . '] process terminated' : 'Worker process terminated';
  1935. $errors = error_get_last();
  1936. if ($errors && ($errors['type'] === \E_ERROR ||
  1937. $errors['type'] === \E_PARSE ||
  1938. $errors['type'] === \E_CORE_ERROR ||
  1939. $errors['type'] === \E_COMPILE_ERROR ||
  1940. $errors['type'] === \E_RECOVERABLE_ERROR)
  1941. ) {
  1942. $errorMsg .= ' with ERROR: ' . static::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\"";
  1943. }
  1944. static::log($errorMsg);
  1945. }
  1946. }
  1947. /**
  1948. * Get error message by error code.
  1949. *
  1950. * @param int $type
  1951. * @return string
  1952. */
  1953. protected static function getErrorType(int $type): string
  1954. {
  1955. return self::ERROR_TYPE[$type] ?? '';
  1956. }
  1957. /**
  1958. * Log.
  1959. *
  1960. * @param mixed $msg
  1961. * @return void
  1962. */
  1963. public static function log(mixed $msg): void
  1964. {
  1965. $msg = $msg . "\n";
  1966. if (!static::$daemonize) {
  1967. static::safeEcho($msg);
  1968. }
  1969. \file_put_contents(static::$logFile, \date('Y-m-d H:i:s') . ' ' . 'pid:'
  1970. . (\DIRECTORY_SEPARATOR === '/' ? \posix_getpid() : 1) . ' ' . $msg, \FILE_APPEND | \LOCK_EX);
  1971. }
  1972. /**
  1973. * Safe Echo.
  1974. * @param string $msg
  1975. * @param bool $decorated
  1976. * @return bool
  1977. */
  1978. public static function safeEcho(string $msg, bool $decorated = false): bool
  1979. {
  1980. $stream = static::outputStream();
  1981. if (!$stream) {
  1982. return false;
  1983. }
  1984. if (!$decorated) {
  1985. $line = $white = $green = $end = '';
  1986. if (static::$outputDecorated) {
  1987. $line = "\033[1A\n\033[K";
  1988. $white = "\033[47;30m";
  1989. $green = "\033[32;40m";
  1990. $end = "\033[0m";
  1991. }
  1992. $msg = \str_replace(['<n>', '<w>', '<g>'], [$line, $white, $green], $msg);
  1993. $msg = \str_replace(['</n>', '</w>', '</g>'], $end, $msg);
  1994. } elseif (!static::$outputDecorated) {
  1995. return false;
  1996. }
  1997. \fwrite($stream, $msg);
  1998. \fflush($stream);
  1999. return true;
  2000. }
  2001. /**
  2002. * set and get output stream.
  2003. *
  2004. * @param resource|null $stream
  2005. * @return false|resource
  2006. */
  2007. private static function outputStream($stream = null)
  2008. {
  2009. if (!$stream) {
  2010. $stream = static::$outputStream ?: \STDOUT;
  2011. }
  2012. if (!$stream || !\is_resource($stream) || 'stream' !== \get_resource_type($stream)) {
  2013. return false;
  2014. }
  2015. $stat = \fstat($stream);
  2016. if (!$stat) {
  2017. return false;
  2018. }
  2019. if (($stat['mode'] & 0170000) === 0100000) { // whether is regular file
  2020. static::$outputDecorated = false;
  2021. } else {
  2022. static::$outputDecorated =
  2023. \DIRECTORY_SEPARATOR === '/' && // linux or unix
  2024. \function_exists('posix_isatty') &&
  2025. \posix_isatty($stream); // whether is interactive terminal
  2026. }
  2027. return static::$outputStream = $stream;
  2028. }
  2029. /**
  2030. * Constructor.
  2031. *
  2032. * @param string|null $socketName
  2033. * @param array $socketContext
  2034. */
  2035. public function __construct(string $socketName = null, array $socketContext = [])
  2036. {
  2037. // Save all worker instances.
  2038. $this->workerId = \spl_object_hash($this);
  2039. $this->context = new stdClass();
  2040. static::$workers[$this->workerId] = $this;
  2041. static::$pidMap[$this->workerId] = [];
  2042. // Context for socket.
  2043. if ($socketName) {
  2044. $this->socketName = $socketName;
  2045. if (!isset($socketContext['socket']['backlog'])) {
  2046. $socketContext['socket']['backlog'] = static::DEFAULT_BACKLOG;
  2047. }
  2048. $this->socketContext = \stream_context_create($socketContext);
  2049. }
  2050. // Try to turn reusePort on.
  2051. /*if (\DIRECTORY_SEPARATOR === '/' // if linux
  2052. && $socketName
  2053. && \version_compare(php_uname('r'), '3.9', 'ge') // if kernel >=3.9
  2054. && \strtolower(\php_uname('s')) !== 'darwin' // if not Mac OS
  2055. && strpos($socketName,'unix') !== 0 // if not unix socket
  2056. && strpos($socketName,'udp') !== 0) { // if not udp socket
  2057. $address = \parse_url($socketName);
  2058. if (isset($address['host']) && isset($address['port'])) {
  2059. try {
  2060. \set_error_handler(function(){});
  2061. // If address not in use, turn reusePort on automatically.
  2062. $server = stream_socket_server("tcp://{$address['host']}:{$address['port']}");
  2063. if ($server) {
  2064. $this->reusePort = true;
  2065. fclose($server);
  2066. }
  2067. \restore_error_handler();
  2068. } catch (\Throwable $e) {}
  2069. }
  2070. }*/
  2071. }
  2072. /**
  2073. * Listen.
  2074. *
  2075. * @throws Exception
  2076. */
  2077. public function listen(): void
  2078. {
  2079. if (!$this->socketName) {
  2080. return;
  2081. }
  2082. if (!$this->mainSocket) {
  2083. $localSocket = $this->parseSocketAddress();
  2084. // Flag.
  2085. $flags = $this->transport === 'udp' ? \STREAM_SERVER_BIND : \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN;
  2086. $errno = 0;
  2087. $errmsg = '';
  2088. // SO_REUSEPORT.
  2089. if ($this->reusePort) {
  2090. \stream_context_set_option($this->socketContext, 'socket', 'so_reuseport', 1);
  2091. }
  2092. // Create an Internet or Unix domain server socket.
  2093. $this->mainSocket = \stream_socket_server($localSocket, $errno, $errmsg, $flags, $this->socketContext);
  2094. if (!$this->mainSocket) {
  2095. throw new Exception($errmsg);
  2096. }
  2097. if ($this->transport === 'ssl') {
  2098. \stream_socket_enable_crypto($this->mainSocket, false);
  2099. } elseif ($this->transport === 'unix') {
  2100. $socketFile = \substr($localSocket, 7);
  2101. if ($this->user) {
  2102. \chown($socketFile, $this->user);
  2103. }
  2104. if ($this->group) {
  2105. \chgrp($socketFile, $this->group);
  2106. }
  2107. }
  2108. // Try to open keepalive for tcp and disable Nagle algorithm.
  2109. if (\function_exists('socket_import_stream') && self::BUILD_IN_TRANSPORTS[$this->transport] === 'tcp') {
  2110. \set_error_handler(function () {
  2111. });
  2112. $socket = \socket_import_stream($this->mainSocket);
  2113. \socket_set_option($socket, \SOL_SOCKET, \SO_KEEPALIVE, 1);
  2114. \socket_set_option($socket, \SOL_TCP, \TCP_NODELAY, 1);
  2115. \restore_error_handler();
  2116. }
  2117. // Non blocking.
  2118. \stream_set_blocking($this->mainSocket, false);
  2119. }
  2120. $this->resumeAccept();
  2121. }
  2122. /**
  2123. * Unlisten.
  2124. *
  2125. * @return void
  2126. */
  2127. public function unlisten(): void
  2128. {
  2129. $this->pauseAccept();
  2130. if ($this->mainSocket) {
  2131. \set_error_handler(function () {
  2132. });
  2133. \fclose($this->mainSocket);
  2134. \restore_error_handler();
  2135. $this->mainSocket = null;
  2136. }
  2137. }
  2138. /**
  2139. * Parse local socket address.
  2140. *
  2141. * @throws Exception
  2142. */
  2143. protected function parseSocketAddress(): ?string
  2144. {
  2145. if (!$this->socketName) {
  2146. return null;
  2147. }
  2148. // Get the application layer communication protocol and listening address.
  2149. list($scheme, $address) = \explode(':', $this->socketName, 2);
  2150. // Check application layer protocol class.
  2151. if (!isset(self::BUILD_IN_TRANSPORTS[$scheme])) {
  2152. $scheme = \ucfirst($scheme);
  2153. $this->protocol = $scheme[0] === '\\' ? $scheme : 'Protocols\\' . $scheme;
  2154. if (!\class_exists($this->protocol)) {
  2155. $this->protocol = "Workerman\\Protocols\\$scheme";
  2156. if (!\class_exists($this->protocol)) {
  2157. throw new \RuntimeException("class \\Protocols\\$scheme not exist");
  2158. }
  2159. }
  2160. if (!isset(self::BUILD_IN_TRANSPORTS[$this->transport])) {
  2161. throw new \RuntimeException('Bad worker->transport ' . \var_export($this->transport, true));
  2162. }
  2163. } else if ($this->transport === 'tcp') {
  2164. $this->transport = $scheme;
  2165. }
  2166. //local socket
  2167. return self::BUILD_IN_TRANSPORTS[$this->transport] . ":" . $address;
  2168. }
  2169. /**
  2170. * Pause accept new connections.
  2171. *
  2172. * @return void
  2173. */
  2174. public function pauseAccept(): void
  2175. {
  2176. if (static::$globalEvent && false === $this->pauseAccept && $this->mainSocket) {
  2177. static::$globalEvent->offReadable($this->mainSocket);
  2178. $this->pauseAccept = true;
  2179. }
  2180. }
  2181. /**
  2182. * Resume accept new connections.
  2183. *
  2184. * @return void
  2185. */
  2186. public function resumeAccept(): void
  2187. {
  2188. // Register a listener to be notified when server socket is ready to read.
  2189. if (static::$globalEvent && true === $this->pauseAccept && $this->mainSocket) {
  2190. if ($this->transport !== 'udp') {
  2191. static::$globalEvent->onReadable($this->mainSocket, [$this, 'acceptTcpConnection']);
  2192. } else {
  2193. static::$globalEvent->onReadable($this->mainSocket, [$this, 'acceptUdpConnection']);
  2194. }
  2195. $this->pauseAccept = false;
  2196. }
  2197. }
  2198. /**
  2199. * Get socket name.
  2200. *
  2201. * @return string
  2202. */
  2203. public function getSocketName(): string
  2204. {
  2205. return $this->socketName ? \lcfirst($this->socketName) : 'none';
  2206. }
  2207. /**
  2208. * Run worker instance.
  2209. *
  2210. * @return void
  2211. * @throws Throwable
  2212. */
  2213. public function run(): void
  2214. {
  2215. $this->listen();
  2216. // Try to emit onWorkerStart callback.
  2217. if ($this->onWorkerStart) {
  2218. try {
  2219. ($this->onWorkerStart)($this);
  2220. } catch (Throwable $e) {
  2221. // Avoid rapid infinite loop exit.
  2222. sleep(1);
  2223. static::stopAll(250, $e);
  2224. }
  2225. }
  2226. }
  2227. /**
  2228. * Stop current worker instance.
  2229. *
  2230. * @return void
  2231. */
  2232. public function stop(): void
  2233. {
  2234. // Try to emit onWorkerStop callback.
  2235. if ($this->onWorkerStop) {
  2236. try {
  2237. ($this->onWorkerStop)($this);
  2238. } catch (Throwable $e) {
  2239. static::log($e);
  2240. }
  2241. }
  2242. // Remove listener for server socket.
  2243. $this->unlisten();
  2244. // Close all connections for the worker.
  2245. if (!static::$gracefulStop) {
  2246. foreach ($this->connections as $connection) {
  2247. $connection->close();
  2248. }
  2249. }
  2250. // Remove worker.
  2251. foreach(static::$workers as $key => $one_worker) {
  2252. if ($one_worker->workerId === $this->workerId) {
  2253. unset(static::$workers[$key]);
  2254. }
  2255. }
  2256. // Clear callback.
  2257. $this->onMessage = $this->onClose = $this->onError = $this->onBufferDrain = $this->onBufferFull = null;
  2258. }
  2259. /**
  2260. * Accept a connection.
  2261. *
  2262. * @param resource $socket
  2263. * @return void
  2264. */
  2265. public function acceptTcpConnection($socket): void
  2266. {
  2267. // Accept a connection on server socket.
  2268. \set_error_handler(function () {
  2269. });
  2270. $newSocket = \stream_socket_accept($socket, 0, $remoteAddress);
  2271. \restore_error_handler();
  2272. // Thundering herd.
  2273. if (!$newSocket) {
  2274. return;
  2275. }
  2276. // TcpConnection.
  2277. $connection = new TcpConnection(static::$globalEvent, $newSocket, $remoteAddress);
  2278. $this->connections[$connection->id] = $connection;
  2279. $connection->worker = $this;
  2280. $connection->protocol = $this->protocol;
  2281. $connection->transport = $this->transport;
  2282. $connection->onMessage = $this->onMessage;
  2283. $connection->onClose = $this->onClose;
  2284. $connection->onError = $this->onError;
  2285. $connection->onBufferDrain = $this->onBufferDrain;
  2286. $connection->onBufferFull = $this->onBufferFull;
  2287. // Try to emit onConnect callback.
  2288. if ($this->onConnect) {
  2289. try {
  2290. ($this->onConnect)($connection);
  2291. } catch (Throwable $e) {
  2292. static::stopAll(250, $e);
  2293. }
  2294. }
  2295. }
  2296. /**
  2297. * For udp package.
  2298. *
  2299. * @param resource $socket
  2300. * @return bool
  2301. */
  2302. public function acceptUdpConnection($socket): bool
  2303. {
  2304. \set_error_handler(function () {
  2305. });
  2306. $recvBuffer = \stream_socket_recvfrom($socket, UdpConnection::MAX_UDP_PACKAGE_SIZE, 0, $remoteAddress);
  2307. \restore_error_handler();
  2308. if (false === $recvBuffer || empty($remoteAddress)) {
  2309. return false;
  2310. }
  2311. // UdpConnection.
  2312. $connection = new UdpConnection($socket, $remoteAddress);
  2313. $connection->protocol = $this->protocol;
  2314. $messageCallback = $this->onMessage;
  2315. if ($messageCallback) {
  2316. try {
  2317. if ($this->protocol !== null) {
  2318. /** @var \Workerman\Protocols\ProtocolInterface $parser */
  2319. $parser = $this->protocol;
  2320. if ($parser && \method_exists($parser, 'input')) {
  2321. while ($recvBuffer !== '') {
  2322. $len = $parser::input($recvBuffer, $connection);
  2323. if ($len === 0)
  2324. return true;
  2325. $package = \substr($recvBuffer, 0, $len);
  2326. $recvBuffer = \substr($recvBuffer, $len);
  2327. $data = $parser::decode($package, $connection);
  2328. if ($data === false) {
  2329. continue;
  2330. }
  2331. $messageCallback($connection, $data);
  2332. }
  2333. } else {
  2334. $data = $parser::decode($recvBuffer, $connection);
  2335. // Discard bad packets.
  2336. if ($data === false) {
  2337. return true;
  2338. }
  2339. $messageCallback($connection, $data);
  2340. }
  2341. } else {
  2342. $messageCallback($connection, $recvBuffer);
  2343. }
  2344. ++ConnectionInterface::$statistics['total_request'];
  2345. } catch (Throwable $e) {
  2346. static::stopAll(250, $e);
  2347. }
  2348. }
  2349. return true;
  2350. }
  2351. /**
  2352. * Check master process is alive
  2353. *
  2354. * @param int $masterPid
  2355. * @return bool
  2356. */
  2357. protected static function checkMasterIsAlive(int $masterPid): bool
  2358. {
  2359. if (empty($masterPid)) {
  2360. return false;
  2361. }
  2362. $masterIsAlive = $masterPid && \posix_kill($masterPid, 0) && \posix_getpid() !== $masterPid;
  2363. if (!$masterIsAlive) {
  2364. return false;
  2365. }
  2366. $cmdline = "/proc/{$masterPid}/cmdline";
  2367. if (!is_readable($cmdline) || empty(static::$processTitle)) {
  2368. return true;
  2369. }
  2370. $content = file_get_contents($cmdline);
  2371. if (empty($content)) {
  2372. return true;
  2373. }
  2374. return stripos($content, static::$processTitle) !== false || stripos($content, 'php') !== false;
  2375. }
  2376. }