Worker.php 79 KB

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