Worker.php 73 KB

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