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