Worker.php 84 KB

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