Worker.php 81 KB

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