Worker.php 78 KB

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