Worker.php 78 KB

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