Workerman.class.php 82 KB

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