Worker.php 77 KB

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