Worker.php 81 KB

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