Worker.php 81 KB

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