Worker.php 78 KB

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