Worker.php 70 KB

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