Worker.php 76 KB

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