Worker.php 81 KB

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