Worker.php 70 KB

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