Worker.php 70 KB

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