Worker.php 61 KB

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