Worker.php 77 KB

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