Worker.php 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264
  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 = OS_TYPE_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 = OS_TYPE_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 !== OS_TYPE_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 !== OS_TYPE_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. *
  589. * @return void
  590. */
  591. protected static function parseCommand()
  592. {
  593. if (static::$_OS !== OS_TYPE_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. if (isset($argv[1])) echo 'Unknown command: ' . $argv[1] . "\n";
  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. if (isset($command)) echo 'Unknown 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 !== OS_TYPE_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 !== OS_TYPE_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 !== OS_TYPE_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 !== OS_TYPE_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 !== OS_TYPE_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 === OS_TYPE_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. if(is_file($file))
  1108. {
  1109. $files[$file] = $file;
  1110. }
  1111. }
  1112. return $files;
  1113. }
  1114. /**
  1115. * Fork one worker process.
  1116. *
  1117. * @param string $start_file
  1118. */
  1119. public static function forkOneWorkerForWindows($start_file)
  1120. {
  1121. $start_file = realpath($start_file);
  1122. $std_file = sys_get_temp_dir() . '/'.str_replace(array('/', "\\", ':'), '_', $start_file).'.out.txt';
  1123. $descriptorspec = array(
  1124. 0 => array('pipe', 'a'), // stdin
  1125. 1 => array('file', $std_file, 'w'), // stdout
  1126. 2 => array('file', $std_file, 'w') // stderr
  1127. );
  1128. $pipes = array();
  1129. $process = proc_open("php \"$start_file\" -q", $descriptorspec, $pipes);
  1130. $std_handler = fopen($std_file, 'a+');
  1131. stream_set_blocking($std_handler, 0);
  1132. if (empty(static::$globalEvent)) {
  1133. static::$globalEvent = new Select();
  1134. Timer::init(static::$globalEvent);
  1135. }
  1136. $timer_id = Timer::add(1, function()use($std_handler)
  1137. {
  1138. echo fread($std_handler, 65535);
  1139. });
  1140. // 保存子进程句柄
  1141. static::$_processForWindows[$start_file] = array($process, $start_file, $timer_id);
  1142. }
  1143. /**
  1144. * check worker status for windows.
  1145. * @return void
  1146. */
  1147. public static function checkWorkerStatusForWindows()
  1148. {
  1149. foreach(static::$_processForWindows as $process_data)
  1150. {
  1151. $process = $process_data[0];
  1152. $start_file = $process_data[1];
  1153. $timer_id = $process_data[2];
  1154. $status = proc_get_status($process);
  1155. if(isset($status['running']))
  1156. {
  1157. if(!$status['running'])
  1158. {
  1159. echo "process $start_file terminated and try to restart\n";
  1160. Timer::del($timer_id);
  1161. @proc_close($process);
  1162. static::forkOneWorkerForWindows($start_file);
  1163. }
  1164. }
  1165. else
  1166. {
  1167. echo "proc_get_status fail\n";
  1168. }
  1169. }
  1170. }
  1171. /**
  1172. * Fork one worker process.
  1173. *
  1174. * @param \Workerman\Worker $worker
  1175. * @throws Exception
  1176. */
  1177. protected static function forkOneWorkerForLinux($worker)
  1178. {
  1179. // Get available worker id.
  1180. $id = static::getId($worker->workerId, 0);
  1181. if ($id === false) {
  1182. return;
  1183. }
  1184. $pid = pcntl_fork();
  1185. // For master process.
  1186. if ($pid > 0) {
  1187. static::$_pidMap[$worker->workerId][$pid] = $pid;
  1188. static::$_idMap[$worker->workerId][$id] = $pid;
  1189. } // For child processes.
  1190. elseif (0 === $pid) {
  1191. if ($worker->reusePort) {
  1192. $worker->listen();
  1193. }
  1194. if (static::$_status === static::STATUS_STARTING) {
  1195. static::resetStd();
  1196. }
  1197. static::$_pidMap = array();
  1198. // Remove other listener.
  1199. foreach(static::$_workers as $key => $one_worker) {
  1200. if ($one_worker->workerId !== $worker->workerId) {
  1201. $one_worker->unlisten();
  1202. unset(static::$_workers[$key]);
  1203. }
  1204. }
  1205. Timer::delAll();
  1206. static::setProcessTitle('WorkerMan: worker process ' . $worker->name . ' ' . $worker->getSocketName());
  1207. $worker->setUserAndGroup();
  1208. $worker->id = $id;
  1209. $worker->run();
  1210. $err = new Exception('event-loop exited');
  1211. static::log($err);
  1212. exit(250);
  1213. } else {
  1214. throw new Exception("forkOneWorker fail");
  1215. }
  1216. }
  1217. /**
  1218. * Get worker id.
  1219. *
  1220. * @param int $worker_id
  1221. * @param int $pid
  1222. *
  1223. * @return integer
  1224. */
  1225. protected static function getId($worker_id, $pid)
  1226. {
  1227. return array_search($pid, static::$_idMap[$worker_id]);
  1228. }
  1229. /**
  1230. * Set unix user and group for current process.
  1231. *
  1232. * @return void
  1233. */
  1234. public function setUserAndGroup()
  1235. {
  1236. // Get uid.
  1237. $user_info = posix_getpwnam($this->user);
  1238. if (!$user_info) {
  1239. static::log("Warning: User {$this->user} not exsits");
  1240. return;
  1241. }
  1242. $uid = $user_info['uid'];
  1243. // Get gid.
  1244. if ($this->group) {
  1245. $group_info = posix_getgrnam($this->group);
  1246. if (!$group_info) {
  1247. static::log("Warning: Group {$this->group} not exsits");
  1248. return;
  1249. }
  1250. $gid = $group_info['gid'];
  1251. } else {
  1252. $gid = $user_info['gid'];
  1253. }
  1254. // Set uid and gid.
  1255. if ($uid != posix_getuid() || $gid != posix_getgid()) {
  1256. if (!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid)) {
  1257. static::log("Warning: change gid or uid fail.");
  1258. }
  1259. }
  1260. }
  1261. /**
  1262. * Set process name.
  1263. *
  1264. * @param string $title
  1265. * @return void
  1266. */
  1267. protected static function setProcessTitle($title)
  1268. {
  1269. // >=php 5.5
  1270. if (function_exists('cli_set_process_title')) {
  1271. @cli_set_process_title($title);
  1272. } // Need proctitle when php<=5.5 .
  1273. elseif (extension_loaded('proctitle') && function_exists('setproctitle')) {
  1274. @setproctitle($title);
  1275. }
  1276. }
  1277. /**
  1278. * Monitor all child processes.
  1279. *
  1280. * @return void
  1281. */
  1282. protected static function monitorWorkers()
  1283. {
  1284. if (static::$_OS === OS_TYPE_LINUX) {
  1285. static::monitorWorkersForLinux();
  1286. } else {
  1287. static::monitorWorkersForWindows();
  1288. }
  1289. }
  1290. /**
  1291. * Monitor all child processes.
  1292. *
  1293. * @return void
  1294. */
  1295. protected static function monitorWorkersForLinux()
  1296. {
  1297. $checkTimes = 0;
  1298. static::$_status = static::STATUS_RUNNING;
  1299. while (1) {
  1300. // Calls signal handlers for pending signals.
  1301. pcntl_signal_dispatch();
  1302. // Suspends execution of the current process until a child has exited, or until a signal is delivered
  1303. $status = 0;
  1304. $pid = pcntl_wait($status, WUNTRACED);
  1305. // Calls signal handlers for pending signals again.
  1306. pcntl_signal_dispatch();
  1307. // If a child has already exited.
  1308. if ($pid > 0) {
  1309. // reset $checkTimes
  1310. $checkTimes = 0;
  1311. // Find out witch worker process exited.
  1312. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1313. if (isset($worker_pid_array[$pid])) {
  1314. $worker = static::$_workers[$worker_id];
  1315. // Exit status.
  1316. if ($status !== 0) {
  1317. static::log("worker[" . $worker->name . ":$pid] exit with status $status");
  1318. }
  1319. // For Statistics.
  1320. if (!isset(static::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
  1321. static::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;
  1322. }
  1323. static::$_globalStatistics['worker_exit_info'][$worker_id][$status]++;
  1324. // Clear process data.
  1325. unset(static::$_pidMap[$worker_id][$pid]);
  1326. // Mark id is available.
  1327. $id = static::getId($worker_id, $pid);
  1328. static::$_idMap[$worker_id][$id] = 0;
  1329. break;
  1330. }
  1331. }
  1332. // Is still running state then fork a new worker process.
  1333. if (static::$_status !== static::STATUS_SHUTDOWN) {
  1334. static::forkWorkers();
  1335. // If reloading continue.
  1336. if (isset(static::$_pidsToRestart[$pid])) {
  1337. unset(static::$_pidsToRestart[$pid]);
  1338. static::reload();
  1339. }
  1340. } else {
  1341. // If shutdown state and all child processes exited then master process exit.
  1342. if (!static::getAllWorkerPids()) {
  1343. static::exitAndClearAll();
  1344. }
  1345. }
  1346. } else {
  1347. // If shutdown state and all child processes exited then master process exit.
  1348. if (static::$_status === static::STATUS_SHUTDOWN) {
  1349. $pids = static::getAllWorkerPids();
  1350. if (!$pids) {
  1351. static::exitAndClearAll();
  1352. } elseif ($checkTimes > 500) {
  1353. // forced stop if all pid exited
  1354. $allExited = true;
  1355. foreach ($pids as $pid) {
  1356. if (posix_kill($pid, 0)) {
  1357. $allExited = false;
  1358. break;
  1359. }
  1360. }
  1361. if ($allExited) {
  1362. static::exitAndClearAll();
  1363. }
  1364. }
  1365. $checkTimes++;
  1366. }
  1367. }
  1368. }
  1369. }
  1370. /**
  1371. * Monitor all child processes.
  1372. *
  1373. * @return void
  1374. */
  1375. protected static function monitorWorkersForWindows()
  1376. {
  1377. Timer::add(0.5, "\\Workerman\\Worker::checkWorkerStatusForWindows");
  1378. static::$globalEvent->loop();
  1379. }
  1380. /**
  1381. * Exit current process.
  1382. *
  1383. * @return void
  1384. */
  1385. protected static function exitAndClearAll()
  1386. {
  1387. foreach (static::$_workers as $worker) {
  1388. $socket_name = $worker->getSocketName();
  1389. if ($worker->transport === 'unix' && $socket_name) {
  1390. list(, $address) = explode(':', $socket_name, 2);
  1391. @unlink($address);
  1392. }
  1393. }
  1394. @unlink(static::$pidFile);
  1395. static::log("Workerman[" . basename(static::$_startFile) . "] has been stopped");
  1396. if (static::$onMasterStop) {
  1397. call_user_func(static::$onMasterStop);
  1398. }
  1399. exit(0);
  1400. }
  1401. /**
  1402. * Execute reload.
  1403. *
  1404. * @return void
  1405. */
  1406. protected static function reload()
  1407. {
  1408. // For master process.
  1409. if (static::$_masterPid === posix_getpid()) {
  1410. // Set reloading state.
  1411. if (static::$_status !== static::STATUS_RELOADING && static::$_status !== static::STATUS_SHUTDOWN) {
  1412. static::log("Workerman[" . basename(static::$_startFile) . "] reloading");
  1413. static::$_status = static::STATUS_RELOADING;
  1414. // Try to emit onMasterReload callback.
  1415. if (static::$onMasterReload) {
  1416. try {
  1417. call_user_func(static::$onMasterReload);
  1418. } catch (\Exception $e) {
  1419. static::log($e);
  1420. exit(250);
  1421. } catch (\Error $e) {
  1422. static::log($e);
  1423. exit(250);
  1424. }
  1425. static::initId();
  1426. }
  1427. }
  1428. if (static::$_gracefulStop) {
  1429. $sig = SIGQUIT;
  1430. } else {
  1431. $sig = SIGUSR1;
  1432. }
  1433. // Send reload signal to all child processes.
  1434. $reloadable_pid_array = array();
  1435. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1436. $worker = static::$_workers[$worker_id];
  1437. if ($worker->reloadable) {
  1438. foreach ($worker_pid_array as $pid) {
  1439. $reloadable_pid_array[$pid] = $pid;
  1440. }
  1441. } else {
  1442. foreach ($worker_pid_array as $pid) {
  1443. // Send reload signal to a worker process which reloadable is false.
  1444. posix_kill($pid, $sig);
  1445. }
  1446. }
  1447. }
  1448. // Get all pids that are waiting reload.
  1449. static::$_pidsToRestart = array_intersect(static::$_pidsToRestart, $reloadable_pid_array);
  1450. // Reload complete.
  1451. if (empty(static::$_pidsToRestart)) {
  1452. if (static::$_status !== static::STATUS_SHUTDOWN) {
  1453. static::$_status = static::STATUS_RUNNING;
  1454. }
  1455. return;
  1456. }
  1457. // Continue reload.
  1458. $one_worker_pid = current(static::$_pidsToRestart);
  1459. // Send reload signal to a worker process.
  1460. posix_kill($one_worker_pid, $sig);
  1461. // If the process does not exit after static::KILL_WORKER_TIMER_TIME seconds try to kill it.
  1462. if(!static::$_gracefulStop){
  1463. Timer::add(static::KILL_WORKER_TIMER_TIME, 'posix_kill', array($one_worker_pid, SIGKILL), false);
  1464. }
  1465. } // For child processes.
  1466. else {
  1467. reset(static::$_workers);
  1468. $worker = current(static::$_workers);
  1469. // Try to emit onWorkerReload callback.
  1470. if ($worker->onWorkerReload) {
  1471. try {
  1472. call_user_func($worker->onWorkerReload, $worker);
  1473. } catch (\Exception $e) {
  1474. static::log($e);
  1475. exit(250);
  1476. } catch (\Error $e) {
  1477. static::log($e);
  1478. exit(250);
  1479. }
  1480. }
  1481. if ($worker->reloadable) {
  1482. static::stopAll();
  1483. }
  1484. }
  1485. }
  1486. /**
  1487. * Stop.
  1488. *
  1489. * @return void
  1490. */
  1491. public static function stopAll()
  1492. {
  1493. static::$_status = static::STATUS_SHUTDOWN;
  1494. // For master process.
  1495. if (static::$_masterPid === posix_getpid()) {
  1496. static::log("Workerman[" . basename(static::$_startFile) . "] stopping ...");
  1497. $worker_pid_array = static::getAllWorkerPids();
  1498. // Send stop signal to all child processes.
  1499. if (static::$_gracefulStop) {
  1500. $sig = SIGTERM;
  1501. } else {
  1502. $sig = SIGINT;
  1503. }
  1504. foreach ($worker_pid_array as $worker_pid) {
  1505. posix_kill($worker_pid, $sig);
  1506. if(!static::$_gracefulStop){
  1507. Timer::add(static::KILL_WORKER_TIMER_TIME, 'posix_kill', array($worker_pid, SIGKILL), false);
  1508. }
  1509. }
  1510. // Remove statistics file.
  1511. if (is_file(static::$_statisticsFile)) {
  1512. @unlink(static::$_statisticsFile);
  1513. }
  1514. } // For child processes.
  1515. else {
  1516. // Execute exit.
  1517. foreach (static::$_workers as $worker) {
  1518. if(!$worker->stopping){
  1519. $worker->stop();
  1520. $worker->stopping = true;
  1521. }
  1522. }
  1523. if (!static::$_gracefulStop || ConnectionInterface::$statistics['connection_count'] <= 0) {
  1524. static::$_workers = array();
  1525. static::$globalEvent->destroy();
  1526. exit(0);
  1527. }
  1528. }
  1529. }
  1530. /**
  1531. * Get process status.
  1532. *
  1533. * @return number
  1534. */
  1535. public static function getStatus()
  1536. {
  1537. return static::$_status;
  1538. }
  1539. /**
  1540. * If stop gracefully.
  1541. *
  1542. * @return boolean
  1543. */
  1544. public static function getGracefulStop()
  1545. {
  1546. return static::$_gracefulStop;
  1547. }
  1548. /**
  1549. * Write statistics data to disk.
  1550. *
  1551. * @return void
  1552. */
  1553. protected static function writeStatisticsToStatusFile()
  1554. {
  1555. // For master process.
  1556. if (static::$_masterPid === posix_getpid()) {
  1557. $all_worker_info = array();
  1558. foreach(static::$_pidMap as $worker_id => $pid_array) {
  1559. /** @var /Workerman/Worker $worker */
  1560. $worker = static::$_workers[$worker_id];
  1561. foreach($pid_array as $pid) {
  1562. $all_worker_info[$pid] = array('name' => $worker->name, 'listen' => $worker->getSocketName());
  1563. }
  1564. }
  1565. file_put_contents(static::$_statisticsFile, json_encode($all_worker_info)."\n", FILE_APPEND);
  1566. $loadavg = function_exists('sys_getloadavg') ? array_map('round', sys_getloadavg(), array(2)) : array('-', '-', '-');
  1567. file_put_contents(static::$_statisticsFile,
  1568. "----------------------------------------------GLOBAL STATUS----------------------------------------------------\n", FILE_APPEND);
  1569. file_put_contents(static::$_statisticsFile,
  1570. 'Workerman version:' . static::VERSION . " PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
  1571. file_put_contents(static::$_statisticsFile, 'start time:' . date('Y-m-d H:i:s',
  1572. 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",
  1573. FILE_APPEND);
  1574. $load_str = 'load average: ' . implode(", ", $loadavg);
  1575. file_put_contents(static::$_statisticsFile,
  1576. str_pad($load_str, 33) . 'event-loop:' . static::getEventLoopName() . "\n", FILE_APPEND);
  1577. file_put_contents(static::$_statisticsFile,
  1578. count(static::$_pidMap) . ' workers ' . count(static::getAllWorkerPids()) . " processes\n",
  1579. FILE_APPEND);
  1580. file_put_contents(static::$_statisticsFile,
  1581. str_pad('worker_name', static::$_maxWorkerNameLength) . " exit_status exit_count\n", FILE_APPEND);
  1582. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1583. $worker = static::$_workers[$worker_id];
  1584. if (isset(static::$_globalStatistics['worker_exit_info'][$worker_id])) {
  1585. foreach (static::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
  1586. file_put_contents(static::$_statisticsFile,
  1587. str_pad($worker->name, static::$_maxWorkerNameLength) . " " . str_pad($worker_exit_status,
  1588. 16) . " $worker_exit_count\n", FILE_APPEND);
  1589. }
  1590. } else {
  1591. file_put_contents(static::$_statisticsFile,
  1592. str_pad($worker->name, static::$_maxWorkerNameLength) . " " . str_pad(0, 16) . " 0\n",
  1593. FILE_APPEND);
  1594. }
  1595. }
  1596. file_put_contents(static::$_statisticsFile,
  1597. "----------------------------------------------PROCESS STATUS---------------------------------------------------\n",
  1598. FILE_APPEND);
  1599. file_put_contents(static::$_statisticsFile,
  1600. "pid\tmemory " . str_pad('listening', static::$_maxSocketNameLength) . " " . str_pad('worker_name',
  1601. static::$_maxWorkerNameLength) . " connections " . str_pad('send_fail', 9) . " "
  1602. . str_pad('timers', 8) . str_pad('total_request', 13) ." qps status\n", FILE_APPEND);
  1603. chmod(static::$_statisticsFile, 0722);
  1604. foreach (static::getAllWorkerPids() as $worker_pid) {
  1605. posix_kill($worker_pid, SIGUSR2);
  1606. }
  1607. return;
  1608. }
  1609. // For child processes.
  1610. reset(static::$_workers);
  1611. /** @var \Workerman\Worker $worker */
  1612. $worker = current(static::$_workers);
  1613. $worker_status_str = posix_getpid() . "\t" . str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M", 7)
  1614. . " " . str_pad($worker->getSocketName(), static::$_maxSocketNameLength) . " "
  1615. . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::$_maxWorkerNameLength)
  1616. . " ";
  1617. $worker_status_str .= str_pad(ConnectionInterface::$statistics['connection_count'], 11)
  1618. . " " . str_pad(ConnectionInterface::$statistics['send_fail'], 9)
  1619. . " " . str_pad(static::$globalEvent->getTimerCount(), 7)
  1620. . " " . str_pad(ConnectionInterface::$statistics['total_request'], 13) . "\n";
  1621. file_put_contents(static::$_statisticsFile, $worker_status_str, FILE_APPEND);
  1622. }
  1623. /**
  1624. * Write statistics data to disk.
  1625. *
  1626. * @return void
  1627. */
  1628. protected static function writeConnectionsStatisticsToStatusFile()
  1629. {
  1630. // For master process.
  1631. if (static::$_masterPid === posix_getpid()) {
  1632. file_put_contents(static::$_statisticsFile, "--------------------------------------------------------------------- WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", FILE_APPEND);
  1633. 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);
  1634. chmod(static::$_statisticsFile, 0722);
  1635. foreach (static::getAllWorkerPids() as $worker_pid) {
  1636. posix_kill($worker_pid, SIGIO);
  1637. }
  1638. return;
  1639. }
  1640. // For child processes.
  1641. $bytes_format = function($bytes)
  1642. {
  1643. if($bytes > 1024*1024*1024*1024) {
  1644. return round($bytes/(1024*1024*1024*1024), 1)."TB";
  1645. }
  1646. if($bytes > 1024*1024*1024) {
  1647. return round($bytes/(1024*1024*1024), 1)."GB";
  1648. }
  1649. if($bytes > 1024*1024) {
  1650. return round($bytes/(1024*1024), 1)."MB";
  1651. }
  1652. if($bytes > 1024) {
  1653. return round($bytes/(1024), 1)."KB";
  1654. }
  1655. return $bytes."B";
  1656. };
  1657. $pid = posix_getpid();
  1658. $str = '';
  1659. reset(static::$_workers);
  1660. $current_worker = current(static::$_workers);
  1661. $default_worker_name = $current_worker->name;
  1662. /** @var \Workerman\Worker $worker */
  1663. foreach(TcpConnection::$connections as $connection) {
  1664. /** @var \Workerman\Connection\TcpConnection $connection */
  1665. $transport = $connection->transport;
  1666. $ipv4 = $connection->isIpV4() ? ' 1' : ' 0';
  1667. $ipv6 = $connection->isIpV6() ? ' 1' : ' 0';
  1668. $recv_q = $bytes_format($connection->getRecvBufferQueueSize());
  1669. $send_q = $bytes_format($connection->getSendBufferQueueSize());
  1670. $local_address = trim($connection->getLocalAddress());
  1671. $remote_address = trim($connection->getRemoteAddress());
  1672. $state = $connection->getStatus(false);
  1673. $bytes_read = $bytes_format($connection->bytesRead);
  1674. $bytes_written = $bytes_format($connection->bytesWritten);
  1675. $id = $connection->id;
  1676. $protocol = $connection->protocol ? $connection->protocol : $connection->transport;
  1677. $pos = strrpos($protocol, '\\');
  1678. if ($pos) {
  1679. $protocol = substr($protocol, $pos+1);
  1680. }
  1681. if (strlen($protocol) > 15) {
  1682. $protocol = substr($protocol, 0, 13) . '..';
  1683. }
  1684. $worker_name = isset($connection->worker) ? $connection->worker->name : $default_worker_name;
  1685. if (strlen($worker_name) > 14) {
  1686. $worker_name = substr($worker_name, 0, 12) . '..';
  1687. }
  1688. $str .= str_pad($pid, 9) . str_pad($worker_name, 16) . str_pad($id, 10) . str_pad($transport, 8)
  1689. . str_pad($protocol, 16) . str_pad($ipv4, 7) . str_pad($ipv6, 7) . str_pad($recv_q, 13)
  1690. . str_pad($send_q, 13) . str_pad($bytes_read, 13) . str_pad($bytes_written, 13) . ' '
  1691. . str_pad($state, 14) . ' ' . str_pad($local_address, 22) . ' ' . str_pad($remote_address, 22) ."\n";
  1692. }
  1693. if ($str) {
  1694. file_put_contents(static::$_statisticsFile, $str, FILE_APPEND);
  1695. }
  1696. }
  1697. /**
  1698. * Check errors when current process exited.
  1699. *
  1700. * @return void
  1701. */
  1702. public static function checkErrors()
  1703. {
  1704. if (static::STATUS_SHUTDOWN != static::$_status) {
  1705. $error_msg = static::$_OS === OS_TYPE_LINUX ? 'Worker['. posix_getpid() .'] process terminated' : 'Worker process terminated';
  1706. $errors = error_get_last();
  1707. if ($errors && ($errors['type'] === E_ERROR ||
  1708. $errors['type'] === E_PARSE ||
  1709. $errors['type'] === E_CORE_ERROR ||
  1710. $errors['type'] === E_COMPILE_ERROR ||
  1711. $errors['type'] === E_RECOVERABLE_ERROR)
  1712. ) {
  1713. $error_msg .= ' with ERROR: ' . static::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\"";
  1714. }
  1715. static::log($error_msg);
  1716. }
  1717. }
  1718. /**
  1719. * Get error message by error code.
  1720. *
  1721. * @param integer $type
  1722. * @return string
  1723. */
  1724. protected static function getErrorType($type)
  1725. {
  1726. switch ($type) {
  1727. case E_ERROR: // 1 //
  1728. return 'E_ERROR';
  1729. case E_WARNING: // 2 //
  1730. return 'E_WARNING';
  1731. case E_PARSE: // 4 //
  1732. return 'E_PARSE';
  1733. case E_NOTICE: // 8 //
  1734. return 'E_NOTICE';
  1735. case E_CORE_ERROR: // 16 //
  1736. return 'E_CORE_ERROR';
  1737. case E_CORE_WARNING: // 32 //
  1738. return 'E_CORE_WARNING';
  1739. case E_COMPILE_ERROR: // 64 //
  1740. return 'E_COMPILE_ERROR';
  1741. case E_COMPILE_WARNING: // 128 //
  1742. return 'E_COMPILE_WARNING';
  1743. case E_USER_ERROR: // 256 //
  1744. return 'E_USER_ERROR';
  1745. case E_USER_WARNING: // 512 //
  1746. return 'E_USER_WARNING';
  1747. case E_USER_NOTICE: // 1024 //
  1748. return 'E_USER_NOTICE';
  1749. case E_STRICT: // 2048 //
  1750. return 'E_STRICT';
  1751. case E_RECOVERABLE_ERROR: // 4096 //
  1752. return 'E_RECOVERABLE_ERROR';
  1753. case E_DEPRECATED: // 8192 //
  1754. return 'E_DEPRECATED';
  1755. case E_USER_DEPRECATED: // 16384 //
  1756. return 'E_USER_DEPRECATED';
  1757. }
  1758. return "";
  1759. }
  1760. /**
  1761. * Log.
  1762. *
  1763. * @param string $msg
  1764. * @return void
  1765. */
  1766. public static function log($msg)
  1767. {
  1768. $msg = $msg . "\n";
  1769. if (!static::$daemonize) {
  1770. static::safeEcho($msg);
  1771. }
  1772. file_put_contents((string)static::$logFile, date('Y-m-d H:i:s') . ' ' . 'pid:'
  1773. . (static::$_OS === OS_TYPE_LINUX ? posix_getpid() : 1) . ' ' . $msg, FILE_APPEND | LOCK_EX);
  1774. }
  1775. /**
  1776. * Safe Echo.
  1777. *
  1778. * @param $msg
  1779. */
  1780. public static function safeEcho($msg)
  1781. {
  1782. if (!function_exists('posix_isatty') || posix_isatty(STDOUT)) {
  1783. echo $msg;
  1784. }
  1785. }
  1786. /**
  1787. * Construct.
  1788. *
  1789. * @param string $socket_name
  1790. * @param array $context_option
  1791. */
  1792. public function __construct($socket_name = '', $context_option = array())
  1793. {
  1794. // Save all worker instances.
  1795. $this->workerId = spl_object_hash($this);
  1796. static::$_workers[$this->workerId] = $this;
  1797. static::$_pidMap[$this->workerId] = array();
  1798. // Get autoload root path.
  1799. $backtrace = debug_backtrace();
  1800. $this->_autoloadRootPath = dirname($backtrace[0]['file']);
  1801. // Context for socket.
  1802. if ($socket_name) {
  1803. $this->_socketName = $socket_name;
  1804. if (!isset($context_option['socket']['backlog'])) {
  1805. $context_option['socket']['backlog'] = static::DEFAULT_BACKLOG;
  1806. }
  1807. $this->_context = stream_context_create($context_option);
  1808. }
  1809. }
  1810. /**
  1811. * Listen.
  1812. *
  1813. * @throws Exception
  1814. */
  1815. public function listen()
  1816. {
  1817. if (!$this->_socketName) {
  1818. return;
  1819. }
  1820. // Autoload.
  1821. Autoloader::setRootPath($this->_autoloadRootPath);
  1822. if (!$this->_mainSocket) {
  1823. // Get the application layer communication protocol and listening address.
  1824. list($scheme, $address) = explode(':', $this->_socketName, 2);
  1825. // Check application layer protocol class.
  1826. if (!isset(static::$_builtinTransports[$scheme])) {
  1827. $scheme = ucfirst($scheme);
  1828. $this->protocol = substr($scheme,0,1)==='\\' ? $scheme : '\\Protocols\\' . $scheme;
  1829. if (!class_exists($this->protocol)) {
  1830. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  1831. if (!class_exists($this->protocol)) {
  1832. throw new Exception("class \\Protocols\\$scheme not exist");
  1833. }
  1834. }
  1835. if (!isset(static::$_builtinTransports[$this->transport])) {
  1836. throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
  1837. }
  1838. } else {
  1839. $this->transport = $scheme;
  1840. }
  1841. $local_socket = static::$_builtinTransports[$this->transport] . ":" . $address;
  1842. // Flag.
  1843. $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
  1844. $errno = 0;
  1845. $errmsg = '';
  1846. // SO_REUSEPORT.
  1847. if ($this->reusePort) {
  1848. stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
  1849. }
  1850. // Create an Internet or Unix domain server socket.
  1851. $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
  1852. if (!$this->_mainSocket) {
  1853. throw new Exception($errmsg);
  1854. }
  1855. if ($this->transport === 'ssl') {
  1856. stream_socket_enable_crypto($this->_mainSocket, false);
  1857. } elseif ($this->transport === 'unix') {
  1858. $socketFile = substr($address, 2);
  1859. if ($this->user) {
  1860. chown($socketFile, $this->user);
  1861. }
  1862. if ($this->group) {
  1863. chgrp($socketFile, $this->group);
  1864. }
  1865. }
  1866. // Try to open keepalive for tcp and disable Nagle algorithm.
  1867. if (function_exists('socket_import_stream') && static::$_builtinTransports[$this->transport] === 'tcp') {
  1868. $socket = socket_import_stream($this->_mainSocket);
  1869. @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  1870. @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
  1871. }
  1872. // Non blocking.
  1873. stream_set_blocking($this->_mainSocket, 0);
  1874. }
  1875. $this->resumeAccept();
  1876. }
  1877. /**
  1878. * Unlisten.
  1879. *
  1880. * @return void
  1881. */
  1882. public function unlisten() {
  1883. $this->pauseAccept();
  1884. if ($this->_mainSocket) {
  1885. @fclose($this->_mainSocket);
  1886. $this->_mainSocket = null;
  1887. }
  1888. }
  1889. /**
  1890. * Pause accept new connections.
  1891. *
  1892. * @return void
  1893. */
  1894. public function pauseAccept()
  1895. {
  1896. if (static::$globalEvent && false === $this->_pauseAccept && $this->_mainSocket) {
  1897. static::$globalEvent->del($this->_mainSocket, EventInterface::EV_READ);
  1898. $this->_pauseAccept = true;
  1899. }
  1900. }
  1901. /**
  1902. * Resume accept new connections.
  1903. *
  1904. * @return void
  1905. */
  1906. public function resumeAccept()
  1907. {
  1908. // Register a listener to be notified when server socket is ready to read.
  1909. if (static::$globalEvent && true === $this->_pauseAccept && $this->_mainSocket) {
  1910. if ($this->transport !== 'udp') {
  1911. static::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
  1912. } else {
  1913. static::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1914. array($this, 'acceptUdpConnection'));
  1915. }
  1916. $this->_pauseAccept = false;
  1917. }
  1918. }
  1919. /**
  1920. * Get socket name.
  1921. *
  1922. * @return string
  1923. */
  1924. public function getSocketName()
  1925. {
  1926. return $this->_socketName ? lcfirst($this->_socketName) : 'none';
  1927. }
  1928. /**
  1929. * Run worker instance.
  1930. *
  1931. * @return void
  1932. */
  1933. public function run()
  1934. {
  1935. //Update process state.
  1936. static::$_status = static::STATUS_RUNNING;
  1937. // Register shutdown function for checking errors.
  1938. register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));
  1939. // Set autoload root path.
  1940. Autoloader::setRootPath($this->_autoloadRootPath);
  1941. // Create a global event loop.
  1942. if (!static::$globalEvent) {
  1943. $event_loop_class = static::getEventLoopName();
  1944. static::$globalEvent = new $event_loop_class;
  1945. $this->resumeAccept();
  1946. }
  1947. // Reinstall signal.
  1948. static::reinstallSignal();
  1949. // Init Timer.
  1950. Timer::init(static::$globalEvent);
  1951. // Set an empty onMessage callback.
  1952. if (empty($this->onMessage)) {
  1953. $this->onMessage = function () {};
  1954. }
  1955. // Try to emit onWorkerStart callback.
  1956. if ($this->onWorkerStart) {
  1957. try {
  1958. call_user_func($this->onWorkerStart, $this);
  1959. } catch (\Exception $e) {
  1960. static::log($e);
  1961. // Avoid rapid infinite loop exit.
  1962. sleep(1);
  1963. exit(250);
  1964. } catch (\Error $e) {
  1965. static::log($e);
  1966. // Avoid rapid infinite loop exit.
  1967. sleep(1);
  1968. exit(250);
  1969. }
  1970. }
  1971. // Main loop.
  1972. static::$globalEvent->loop();
  1973. }
  1974. /**
  1975. * Stop current worker instance.
  1976. *
  1977. * @return void
  1978. */
  1979. public function stop()
  1980. {
  1981. // Try to emit onWorkerStop callback.
  1982. if ($this->onWorkerStop) {
  1983. try {
  1984. call_user_func($this->onWorkerStop, $this);
  1985. } catch (\Exception $e) {
  1986. static::log($e);
  1987. exit(250);
  1988. } catch (\Error $e) {
  1989. static::log($e);
  1990. exit(250);
  1991. }
  1992. }
  1993. // Remove listener for server socket.
  1994. $this->unlisten();
  1995. // Close all connections for the worker.
  1996. if (!static::$_gracefulStop) {
  1997. foreach ($this->connections as $connection) {
  1998. $connection->close();
  1999. }
  2000. }
  2001. // Clear callback.
  2002. $this->onMessage = $this->onClose = $this->onError = $this->onBufferDrain = $this->onBufferFull = null;
  2003. }
  2004. /**
  2005. * Accept a connection.
  2006. *
  2007. * @param resource $socket
  2008. * @return void
  2009. */
  2010. public function acceptConnection($socket)
  2011. {
  2012. // Accept a connection on server socket.
  2013. $new_socket = @stream_socket_accept($socket, 0, $remote_address);
  2014. // Thundering herd.
  2015. if (!$new_socket) {
  2016. return;
  2017. }
  2018. // TcpConnection.
  2019. $connection = new TcpConnection($new_socket, $remote_address);
  2020. $this->connections[$connection->id] = $connection;
  2021. $connection->worker = $this;
  2022. $connection->protocol = $this->protocol;
  2023. $connection->transport = $this->transport;
  2024. $connection->onMessage = $this->onMessage;
  2025. $connection->onClose = $this->onClose;
  2026. $connection->onError = $this->onError;
  2027. $connection->onBufferDrain = $this->onBufferDrain;
  2028. $connection->onBufferFull = $this->onBufferFull;
  2029. // Try to emit onConnect callback.
  2030. if ($this->onConnect) {
  2031. try {
  2032. call_user_func($this->onConnect, $connection);
  2033. } catch (\Exception $e) {
  2034. static::log($e);
  2035. exit(250);
  2036. } catch (\Error $e) {
  2037. static::log($e);
  2038. exit(250);
  2039. }
  2040. }
  2041. }
  2042. /**
  2043. * For udp package.
  2044. *
  2045. * @param resource $socket
  2046. * @return bool
  2047. */
  2048. public function acceptUdpConnection($socket)
  2049. {
  2050. $recv_buffer = stream_socket_recvfrom($socket, static::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
  2051. if (false === $recv_buffer || empty($remote_address)) {
  2052. return false;
  2053. }
  2054. // UdpConnection.
  2055. $connection = new UdpConnection($socket, $remote_address);
  2056. $connection->protocol = $this->protocol;
  2057. if ($this->onMessage) {
  2058. if ($this->protocol !== null) {
  2059. /** @var \Workerman\Protocols\ProtocolInterface $parser */
  2060. $parser = $this->protocol;
  2061. $recv_buffer = $parser::decode($recv_buffer, $connection);
  2062. // Discard bad packets.
  2063. if ($recv_buffer === false)
  2064. return true;
  2065. }
  2066. ConnectionInterface::$statistics['total_request']++;
  2067. try {
  2068. call_user_func($this->onMessage, $connection, $recv_buffer);
  2069. } catch (\Exception $e) {
  2070. static::log($e);
  2071. exit(250);
  2072. } catch (\Error $e) {
  2073. static::log($e);
  2074. exit(250);
  2075. }
  2076. }
  2077. return true;
  2078. }
  2079. }