Worker.php 79 KB

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