Worker.php 81 KB

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