Worker.php 78 KB

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