Worker.php 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940
  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. posix_kill($master_pid, SIGUSR1);
  680. self::log("Workerman[$start_file] reload");
  681. exit;
  682. default :
  683. exit($usage);
  684. }
  685. }
  686. /**
  687. * Format status data.
  688. *
  689. * @return string
  690. */
  691. protected static function formatStatusData()
  692. {
  693. static $total_request_cache = array();
  694. $info = @file(self::$_statisticsFile, FILE_IGNORE_NEW_LINES);
  695. if (!$info) {
  696. return '';
  697. }
  698. $status_str = '';
  699. $current_total_request = array();
  700. $worker_info = json_decode($info[0], true);
  701. ksort($worker_info, SORT_NUMERIC);
  702. unset($info[0]);
  703. $data_waiting_sort = array();
  704. $read_process_status = false;
  705. foreach($info as $key => $value) {
  706. if (!$read_process_status) {
  707. $status_str .= $value . "\n";
  708. if (preg_match('/^pid.*?memory.*?listening/', $value)) {
  709. $read_process_status = true;
  710. }
  711. continue;
  712. }
  713. if(preg_match('/^[0-9]+/', $value, $pid_math)) {
  714. $pid = $pid_math[0];
  715. $data_waiting_sort[$pid] = $value;
  716. if(preg_match('/^\S+?\s+?\S+?\s+?\S+?\s+?\S+?\s+?\S+?\s+?\S+?\s+?\S+?\s+?(\S+?)\s+?/', $value, $match)) {
  717. $current_total_request[$pid] = $match[1];
  718. }
  719. }
  720. }
  721. foreach($worker_info as $pid => $info) {
  722. if (!isset($data_waiting_sort[$pid])) {
  723. $status_str .= "$pid\t" . str_pad('N/A', 7) . " "
  724. . str_pad($info['listen'], self::$_maxSocketNameLength) . " "
  725. . str_pad($info['name'], self::$_maxWorkerNameLength) . " "
  726. . str_pad('N/A', 11) . " " . str_pad('N/A', 9) . " "
  727. . str_pad('N/A', 7) . " " . str_pad('N/A', 13) . " N/A [busy] \n";
  728. continue;
  729. }
  730. //$qps = isset($total_request_cache[$pid]) ? $current_total_request[$pid]
  731. if (!isset($total_request_cache[$pid]) || !isset($current_total_request[$pid])) {
  732. $qps = 0;
  733. } else {
  734. $qps = $current_total_request[$pid] - $total_request_cache[$pid];
  735. }
  736. $status_str .= $data_waiting_sort[$pid]. " " . str_pad($qps, 6) ." [idle]\n";
  737. }
  738. $total_request_cache = $current_total_request;
  739. return $status_str;
  740. }
  741. /**
  742. * Install signal handler.
  743. *
  744. * @return void
  745. */
  746. protected static function installSignal()
  747. {
  748. // stop
  749. pcntl_signal(SIGINT, array('\Workerman\Worker', 'signalHandler'), false);
  750. // graceful stop
  751. pcntl_signal(SIGTERM, array('\Workerman\Worker', 'signalHandler'), false);
  752. // reload
  753. pcntl_signal(SIGUSR1, array('\Workerman\Worker', 'signalHandler'), false);
  754. // status
  755. pcntl_signal(SIGUSR2, array('\Workerman\Worker', 'signalHandler'), false);
  756. // connection status
  757. pcntl_signal(SIGIO, array('\Workerman\Worker', 'signalHandler'), false);
  758. // ignore
  759. pcntl_signal(SIGPIPE, SIG_IGN, false);
  760. }
  761. /**
  762. * Reinstall signal handler.
  763. *
  764. * @return void
  765. */
  766. protected static function reinstallSignal()
  767. {
  768. // uninstall stop signal handler
  769. pcntl_signal(SIGINT, SIG_IGN, false);
  770. // uninstall graceful stop signal handler
  771. pcntl_signal(SIGTERM, SIG_IGN, false);
  772. // uninstall reload signal handler
  773. pcntl_signal(SIGUSR1, SIG_IGN, false);
  774. // uninstall status signal handler
  775. pcntl_signal(SIGUSR2, SIG_IGN, false);
  776. // reinstall stop signal handler
  777. self::$globalEvent->add(SIGINT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  778. // reinstall graceful stop signal handler
  779. self::$globalEvent->add(SIGTERM, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  780. // reinstall reload signal handler
  781. self::$globalEvent->add(SIGUSR1, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  782. // reinstall status signal handler
  783. self::$globalEvent->add(SIGUSR2, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  784. // reinstall connection status signal handler
  785. self::$globalEvent->add(SIGIO, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  786. }
  787. /**
  788. * Signal handler.
  789. *
  790. * @param int $signal
  791. */
  792. public static function signalHandler($signal)
  793. {
  794. switch ($signal) {
  795. // Stop.
  796. case SIGINT:
  797. self::$_gracefulStop = false;
  798. self::stopAll();
  799. break;
  800. // Graceful stop.
  801. case SIGTERM:
  802. self::$_gracefulStop = true;
  803. self::stopAll();
  804. // Reload.
  805. case SIGUSR1:
  806. self::$_pidsToRestart = self::getAllWorkerPids();
  807. self::reload();
  808. break;
  809. // Show status.
  810. case SIGUSR2:
  811. self::writeStatisticsToStatusFile();
  812. break;
  813. // Show connection status.
  814. case SIGIO:
  815. self::writeConnectionsStatisticsToStatusFile();
  816. break;
  817. }
  818. }
  819. /**
  820. * Run as deamon mode.
  821. *
  822. * @throws Exception
  823. */
  824. protected static function daemonize()
  825. {
  826. if (!self::$daemonize) {
  827. return;
  828. }
  829. umask(0);
  830. $pid = pcntl_fork();
  831. if (-1 === $pid) {
  832. throw new Exception('fork fail');
  833. } elseif ($pid > 0) {
  834. exit(0);
  835. }
  836. if (-1 === posix_setsid()) {
  837. throw new Exception("setsid fail");
  838. }
  839. // Fork again avoid SVR4 system regain the control of terminal.
  840. $pid = pcntl_fork();
  841. if (-1 === $pid) {
  842. throw new Exception("fork fail");
  843. } elseif (0 !== $pid) {
  844. exit(0);
  845. }
  846. }
  847. /**
  848. * Redirect standard input and output.
  849. *
  850. * @throws Exception
  851. */
  852. public static function resetStd()
  853. {
  854. if (!self::$daemonize) {
  855. return;
  856. }
  857. global $STDOUT, $STDERR;
  858. $handle = fopen(self::$stdoutFile, "a");
  859. if ($handle) {
  860. unset($handle);
  861. @fclose(STDOUT);
  862. @fclose(STDERR);
  863. $STDOUT = fopen(self::$stdoutFile, "a");
  864. $STDERR = fopen(self::$stdoutFile, "a");
  865. } else {
  866. throw new Exception('can not open stdoutFile ' . self::$stdoutFile);
  867. }
  868. }
  869. /**
  870. * Save pid.
  871. *
  872. * @throws Exception
  873. */
  874. protected static function saveMasterPid()
  875. {
  876. self::$_masterPid = posix_getpid();
  877. if (false === @file_put_contents(self::$pidFile, self::$_masterPid)) {
  878. throw new Exception('can not save pid to ' . self::$pidFile);
  879. }
  880. }
  881. /**
  882. * Get event loop name.
  883. *
  884. * @return string
  885. */
  886. protected static function getEventLoopName()
  887. {
  888. if (self::$eventLoopClass) {
  889. return self::$eventLoopClass;
  890. }
  891. $loop_name = '';
  892. foreach (self::$_availableEventLoops as $name=>$class) {
  893. if (extension_loaded($name)) {
  894. $loop_name = $name;
  895. break;
  896. }
  897. }
  898. if ($loop_name) {
  899. if (interface_exists('\React\EventLoop\LoopInterface')) {
  900. switch ($loop_name) {
  901. case 'libevent':
  902. self::$eventLoopClass = '\Workerman\Events\React\LibEventLoop';
  903. break;
  904. case 'event':
  905. self::$eventLoopClass = '\Workerman\Events\React\ExtEventLoop';
  906. break;
  907. default :
  908. self::$eventLoopClass = '\Workerman\Events\React\StreamSelectLoop';
  909. break;
  910. }
  911. } else {
  912. self::$eventLoopClass = self::$_availableEventLoops[$loop_name];
  913. }
  914. } else {
  915. self::$eventLoopClass = interface_exists('\React\EventLoop\LoopInterface')? '\Workerman\Events\React\StreamSelectLoop':'\Workerman\Events\Select';
  916. }
  917. return self::$eventLoopClass;
  918. }
  919. /**
  920. * Get all pids of worker processes.
  921. *
  922. * @return array
  923. */
  924. protected static function getAllWorkerPids()
  925. {
  926. $pid_array = array();
  927. foreach (self::$_pidMap as $worker_pid_array) {
  928. foreach ($worker_pid_array as $worker_pid) {
  929. $pid_array[$worker_pid] = $worker_pid;
  930. }
  931. }
  932. return $pid_array;
  933. }
  934. /**
  935. * Fork some worker processes.
  936. *
  937. * @return void
  938. */
  939. protected static function forkWorkers()
  940. {
  941. foreach (self::$_workers as $worker) {
  942. if (self::$_status === self::STATUS_STARTING) {
  943. if (empty($worker->name)) {
  944. $worker->name = $worker->getSocketName();
  945. }
  946. $worker_name_length = strlen($worker->name);
  947. if (self::$_maxWorkerNameLength < $worker_name_length) {
  948. self::$_maxWorkerNameLength = $worker_name_length;
  949. }
  950. }
  951. $worker->count = $worker->count <= 0 ? 1 : $worker->count;
  952. while (count(self::$_pidMap[$worker->workerId]) < $worker->count) {
  953. static::forkOneWorker($worker);
  954. }
  955. }
  956. }
  957. /**
  958. * Fork one worker process.
  959. *
  960. * @param Worker $worker
  961. * @throws Exception
  962. */
  963. protected static function forkOneWorker($worker)
  964. {
  965. // Get available worker id.
  966. $id = self::getId($worker->workerId, 0);
  967. if ($id === false) {
  968. return;
  969. }
  970. $pid = pcntl_fork();
  971. // For master process.
  972. if ($pid > 0) {
  973. self::$_pidMap[$worker->workerId][$pid] = $pid;
  974. self::$_idMap[$worker->workerId][$id] = $pid;
  975. } // For child processes.
  976. elseif (0 === $pid) {
  977. if ($worker->reusePort) {
  978. $worker->listen();
  979. }
  980. if (self::$_status === self::STATUS_STARTING) {
  981. self::resetStd();
  982. }
  983. self::$_pidMap = array();
  984. self::$_workers = array($worker->workerId => $worker);
  985. Timer::delAll();
  986. self::setProcessTitle('WorkerMan: worker process ' . $worker->name . ' ' . $worker->getSocketName());
  987. $worker->setUserAndGroup();
  988. $worker->id = $id;
  989. $worker->run();
  990. $err = new Exception('event-loop exited');
  991. self::log($err);
  992. exit(250);
  993. } else {
  994. throw new Exception("forkOneWorker fail");
  995. }
  996. }
  997. /**
  998. * Get worker id.
  999. *
  1000. * @param int $worker_id
  1001. * @param int $pid
  1002. *
  1003. * @return integer
  1004. */
  1005. protected static function getId($worker_id, $pid)
  1006. {
  1007. return array_search($pid, self::$_idMap[$worker_id]);
  1008. }
  1009. /**
  1010. * Set unix user and group for current process.
  1011. *
  1012. * @return void
  1013. */
  1014. public function setUserAndGroup()
  1015. {
  1016. // Get uid.
  1017. $user_info = posix_getpwnam($this->user);
  1018. if (!$user_info) {
  1019. self::log("Warning: User {$this->user} not exsits");
  1020. return;
  1021. }
  1022. $uid = $user_info['uid'];
  1023. // Get gid.
  1024. if ($this->group) {
  1025. $group_info = posix_getgrnam($this->group);
  1026. if (!$group_info) {
  1027. self::log("Warning: Group {$this->group} not exsits");
  1028. return;
  1029. }
  1030. $gid = $group_info['gid'];
  1031. } else {
  1032. $gid = $user_info['gid'];
  1033. }
  1034. // Set uid and gid.
  1035. if ($uid != posix_getuid() || $gid != posix_getgid()) {
  1036. if (!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid)) {
  1037. self::log("Warning: change gid or uid fail.");
  1038. }
  1039. }
  1040. }
  1041. /**
  1042. * Set process name.
  1043. *
  1044. * @param string $title
  1045. * @return void
  1046. */
  1047. protected static function setProcessTitle($title)
  1048. {
  1049. // >=php 5.5
  1050. if (function_exists('cli_set_process_title')) {
  1051. @cli_set_process_title($title);
  1052. } // Need proctitle when php<=5.5 .
  1053. elseif (extension_loaded('proctitle') && function_exists('setproctitle')) {
  1054. @setproctitle($title);
  1055. }
  1056. }
  1057. /**
  1058. * Monitor all child processes.
  1059. *
  1060. * @return void
  1061. */
  1062. protected static function monitorWorkers()
  1063. {
  1064. self::$_status = self::STATUS_RUNNING;
  1065. while (1) {
  1066. // Calls signal handlers for pending signals.
  1067. pcntl_signal_dispatch();
  1068. // Suspends execution of the current process until a child has exited, or until a signal is delivered
  1069. $status = 0;
  1070. $pid = pcntl_wait($status, WUNTRACED);
  1071. // Calls signal handlers for pending signals again.
  1072. pcntl_signal_dispatch();
  1073. // If a child has already exited.
  1074. if ($pid > 0) {
  1075. // Find out witch worker process exited.
  1076. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  1077. if (isset($worker_pid_array[$pid])) {
  1078. $worker = self::$_workers[$worker_id];
  1079. // Exit status.
  1080. if ($status !== 0) {
  1081. self::log("worker[" . $worker->name . ":$pid] exit with status $status");
  1082. }
  1083. // For Statistics.
  1084. if (!isset(self::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
  1085. self::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;
  1086. }
  1087. self::$_globalStatistics['worker_exit_info'][$worker_id][$status]++;
  1088. // Clear process data.
  1089. unset(self::$_pidMap[$worker_id][$pid]);
  1090. // Mark id is available.
  1091. $id = self::getId($worker_id, $pid);
  1092. self::$_idMap[$worker_id][$id] = 0;
  1093. break;
  1094. }
  1095. }
  1096. // Is still running state then fork a new worker process.
  1097. if (self::$_status !== self::STATUS_SHUTDOWN) {
  1098. self::forkWorkers();
  1099. // If reloading continue.
  1100. if (isset(self::$_pidsToRestart[$pid])) {
  1101. unset(self::$_pidsToRestart[$pid]);
  1102. self::reload();
  1103. }
  1104. } else {
  1105. // If shutdown state and all child processes exited then master process exit.
  1106. if (!self::getAllWorkerPids()) {
  1107. self::exitAndClearAll();
  1108. }
  1109. }
  1110. } else {
  1111. // If shutdown state and all child processes exited then master process exit.
  1112. if (self::$_status === self::STATUS_SHUTDOWN && !self::getAllWorkerPids()) {
  1113. self::exitAndClearAll();
  1114. }
  1115. }
  1116. }
  1117. }
  1118. /**
  1119. * Exit current process.
  1120. *
  1121. * @return void
  1122. */
  1123. protected static function exitAndClearAll()
  1124. {
  1125. foreach (self::$_workers as $worker) {
  1126. $socket_name = $worker->getSocketName();
  1127. if ($worker->transport === 'unix' && $socket_name) {
  1128. list(, $address) = explode(':', $socket_name, 2);
  1129. @unlink($address);
  1130. }
  1131. }
  1132. @unlink(self::$pidFile);
  1133. self::log("Workerman[" . basename(self::$_startFile) . "] has been stopped");
  1134. if (self::$onMasterStop) {
  1135. call_user_func(self::$onMasterStop);
  1136. }
  1137. exit(0);
  1138. }
  1139. /**
  1140. * Execute reload.
  1141. *
  1142. * @return void
  1143. */
  1144. protected static function reload()
  1145. {
  1146. // For master process.
  1147. if (self::$_masterPid === posix_getpid()) {
  1148. // Set reloading state.
  1149. if (self::$_status !== self::STATUS_RELOADING && self::$_status !== self::STATUS_SHUTDOWN) {
  1150. self::log("Workerman[" . basename(self::$_startFile) . "] reloading");
  1151. self::$_status = self::STATUS_RELOADING;
  1152. // Try to emit onMasterReload callback.
  1153. if (self::$onMasterReload) {
  1154. try {
  1155. call_user_func(self::$onMasterReload);
  1156. } catch (\Exception $e) {
  1157. self::log($e);
  1158. exit(250);
  1159. } catch (\Error $e) {
  1160. self::log($e);
  1161. exit(250);
  1162. }
  1163. self::initId();
  1164. }
  1165. }
  1166. // Send reload signal to all child processes.
  1167. $reloadable_pid_array = array();
  1168. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  1169. $worker = self::$_workers[$worker_id];
  1170. if ($worker->reloadable) {
  1171. foreach ($worker_pid_array as $pid) {
  1172. $reloadable_pid_array[$pid] = $pid;
  1173. }
  1174. } else {
  1175. foreach ($worker_pid_array as $pid) {
  1176. // Send reload signal to a worker process which reloadable is false.
  1177. posix_kill($pid, SIGUSR1);
  1178. }
  1179. }
  1180. }
  1181. // Get all pids that are waiting reload.
  1182. self::$_pidsToRestart = array_intersect(self::$_pidsToRestart, $reloadable_pid_array);
  1183. // Reload complete.
  1184. if (empty(self::$_pidsToRestart)) {
  1185. if (self::$_status !== self::STATUS_SHUTDOWN) {
  1186. self::$_status = self::STATUS_RUNNING;
  1187. }
  1188. return;
  1189. }
  1190. // Continue reload.
  1191. $one_worker_pid = current(self::$_pidsToRestart);
  1192. // Send reload signal to a worker process.
  1193. posix_kill($one_worker_pid, SIGUSR1);
  1194. // If the process does not exit after self::KILL_WORKER_TIMER_TIME seconds try to kill it.
  1195. Timer::add(self::KILL_WORKER_TIMER_TIME, 'posix_kill', array($one_worker_pid, SIGKILL), false);
  1196. } // For child processes.
  1197. else {
  1198. reset(self::$_workers);
  1199. $worker = current(self::$_workers);
  1200. // Try to emit onWorkerReload callback.
  1201. if ($worker->onWorkerReload) {
  1202. try {
  1203. call_user_func($worker->onWorkerReload, $worker);
  1204. } catch (\Exception $e) {
  1205. self::log($e);
  1206. exit(250);
  1207. } catch (\Error $e) {
  1208. self::log($e);
  1209. exit(250);
  1210. }
  1211. }
  1212. if ($worker->reloadable) {
  1213. self::stopAll();
  1214. }
  1215. }
  1216. }
  1217. /**
  1218. * Stop.
  1219. *
  1220. * @return void
  1221. */
  1222. public static function stopAll()
  1223. {
  1224. self::$_status = self::STATUS_SHUTDOWN;
  1225. // For master process.
  1226. if (self::$_masterPid === posix_getpid()) {
  1227. self::log("Workerman[" . basename(self::$_startFile) . "] Stopping ...");
  1228. $worker_pid_array = self::getAllWorkerPids();
  1229. // Send stop signal to all child processes.
  1230. if(self::$_gracefulStop){
  1231. $sig = SIGTERM;
  1232. }else{
  1233. $sig = SIGINT;
  1234. }
  1235. foreach ($worker_pid_array as $worker_pid) {
  1236. posix_kill($worker_pid, $sig);
  1237. if(!self::$_gracefulStop){
  1238. Timer::add(self::KILL_WORKER_TIMER_TIME, 'posix_kill', array($worker_pid, SIGKILL), false);
  1239. }
  1240. }
  1241. // Remove statistics file.
  1242. if (is_file(self::$_statisticsFile)) {
  1243. @unlink(self::$_statisticsFile);
  1244. }
  1245. } // For child processes.
  1246. else {
  1247. // Execute exit.
  1248. foreach (self::$_workers as $worker) {
  1249. $worker->stop();
  1250. }
  1251. if(!self::$_gracefulStop) {
  1252. self::$globalEvent->destroy();
  1253. exit(0);
  1254. }
  1255. }
  1256. }
  1257. /**
  1258. * Get process status.
  1259. *
  1260. * @return number
  1261. */
  1262. public static function getStatus(){
  1263. return self::$_status;
  1264. }
  1265. /**
  1266. * If stop gracefully.
  1267. *
  1268. * @return number
  1269. */
  1270. public static function getGracefulStop(){
  1271. return self::$_gracefulStop;
  1272. }
  1273. /**
  1274. * Write statistics data to disk.
  1275. *
  1276. * @return void
  1277. */
  1278. protected static function writeStatisticsToStatusFile()
  1279. {
  1280. // For master process.
  1281. if (self::$_masterPid === posix_getpid()) {
  1282. $all_worker_info = array();
  1283. foreach(self::$_pidMap as $worker_id => $pid_array) {
  1284. /** @var Worker $worker */
  1285. $worker = self::$_workers[$worker_id];
  1286. foreach($pid_array as $pid) {
  1287. $all_worker_info[$pid] = array('name' => $worker->name, 'listen' => $worker->getSocketName());
  1288. }
  1289. }
  1290. file_put_contents(self::$_statisticsFile, json_encode($all_worker_info)."\n", FILE_APPEND);
  1291. $loadavg = function_exists('sys_getloadavg') ? array_map('round', sys_getloadavg(), array(2)) : array('-', '-', '-');
  1292. file_put_contents(self::$_statisticsFile,
  1293. "----------------------------------------------GLOBAL STATUS----------------------------------------------------\n", FILE_APPEND);
  1294. file_put_contents(self::$_statisticsFile,
  1295. 'Workerman version:' . Worker::VERSION . " PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
  1296. file_put_contents(self::$_statisticsFile, 'start time:' . date('Y-m-d H:i:s',
  1297. 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",
  1298. FILE_APPEND);
  1299. $load_str = 'load average: ' . implode(", ", $loadavg);
  1300. file_put_contents(self::$_statisticsFile,
  1301. str_pad($load_str, 33) . 'event-loop:' . self::getEventLoopName() . "\n", FILE_APPEND);
  1302. file_put_contents(self::$_statisticsFile,
  1303. count(self::$_pidMap) . ' workers ' . count(self::getAllWorkerPids()) . " processes\n",
  1304. FILE_APPEND);
  1305. file_put_contents(self::$_statisticsFile,
  1306. str_pad('worker_name', self::$_maxWorkerNameLength) . " exit_status exit_count\n", FILE_APPEND);
  1307. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  1308. $worker = self::$_workers[$worker_id];
  1309. if (isset(self::$_globalStatistics['worker_exit_info'][$worker_id])) {
  1310. foreach (self::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
  1311. file_put_contents(self::$_statisticsFile,
  1312. str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad($worker_exit_status,
  1313. 16) . " $worker_exit_count\n", FILE_APPEND);
  1314. }
  1315. } else {
  1316. file_put_contents(self::$_statisticsFile,
  1317. str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad(0, 16) . " 0\n",
  1318. FILE_APPEND);
  1319. }
  1320. }
  1321. file_put_contents(self::$_statisticsFile,
  1322. "----------------------------------------------PROCESS STATUS---------------------------------------------------\n",
  1323. FILE_APPEND);
  1324. file_put_contents(self::$_statisticsFile,
  1325. "pid\tmemory " . str_pad('listening', self::$_maxSocketNameLength) . " " . str_pad('worker_name',
  1326. self::$_maxWorkerNameLength) . " connections " . str_pad('send_fail', 9) . " "
  1327. . str_pad('timers', 8) . str_pad('total_request', 13) ." qps status\n", FILE_APPEND);
  1328. chmod(self::$_statisticsFile, 0722);
  1329. foreach (self::getAllWorkerPids() as $worker_pid) {
  1330. posix_kill($worker_pid, SIGUSR2);
  1331. }
  1332. return;
  1333. }
  1334. // For child processes.
  1335. /** @var Worker $worker */
  1336. $worker = current(self::$_workers);
  1337. $worker_status_str = posix_getpid() . "\t" . str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M", 7)
  1338. . " " . str_pad($worker->getSocketName(), self::$_maxSocketNameLength) . " "
  1339. . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), self::$_maxWorkerNameLength)
  1340. . " ";
  1341. $worker_status_str .= str_pad(ConnectionInterface::$statistics['connection_count'], 11)
  1342. . " " . str_pad(ConnectionInterface::$statistics['send_fail'], 9)
  1343. . " " . str_pad(self::$globalEvent->getTimerCount(), 7)
  1344. . " " . str_pad(ConnectionInterface::$statistics['total_request'], 13) . "\n";
  1345. file_put_contents(self::$_statisticsFile, $worker_status_str, FILE_APPEND);
  1346. }
  1347. /**
  1348. * Write statistics data to disk.
  1349. *
  1350. * @return void
  1351. */
  1352. protected static function writeConnectionsStatisticsToStatusFile()
  1353. {
  1354. // For master process.
  1355. if (self::$_masterPid === posix_getpid()) {
  1356. file_put_contents(self::$_statisticsFile, "--------------------------------------------------------------------- WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", FILE_APPEND);
  1357. 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);
  1358. chmod(self::$_statisticsFile, 0722);
  1359. foreach (self::getAllWorkerPids() as $worker_pid) {
  1360. posix_kill($worker_pid, SIGIO);
  1361. }
  1362. return;
  1363. }
  1364. // For child processes.
  1365. $bytes_format = function($bytes)
  1366. {
  1367. if($bytes > 1024*1024*1024*1024) {
  1368. return round($bytes/(1024*1024*1024*1024), 1)."TB";
  1369. }
  1370. if($bytes > 1024*1024*1024) {
  1371. return round($bytes/(1024*1024*1024), 1)."GB";
  1372. }
  1373. if($bytes > 1024*1024) {
  1374. return round($bytes/(1024*1024), 1)."MB";
  1375. }
  1376. if($bytes > 1024) {
  1377. return round($bytes/(1024), 1)."KB";
  1378. }
  1379. return $bytes."B";
  1380. };
  1381. $pid = posix_getpid();
  1382. $str = '';
  1383. reset(self::$_workers);
  1384. $current_worker = current(self::$_workers);
  1385. $default_worker_name = $current_worker->name;
  1386. /** @var Worker $worker */
  1387. foreach(TcpConnection::$connections as $connection) {
  1388. /** @var Connection\TcpConnection $connection */
  1389. $transport = $connection->transport;
  1390. $ipv4 = $connection->isIpV4() ? ' 1' : ' 0';
  1391. $ipv6 = $connection->isIpV6() ? ' 1' : ' 0';
  1392. $recv_q = $bytes_format($connection->getRecvBufferQueueSize());
  1393. $send_q = $bytes_format($connection->getSendBufferQueueSize());
  1394. $local_address = trim($connection->getLocalAddress());
  1395. $remote_address = trim($connection->getRemoteAddress());
  1396. $state = $connection->getStatus(false);
  1397. $bytes_read = $bytes_format($connection->bytesRead);
  1398. $bytes_written = $bytes_format($connection->bytesWritten);
  1399. $id = $connection->id;
  1400. $protocol = $connection->protocol ? $connection->protocol : $connection->transport;
  1401. $pos = strrpos($protocol, '\\');
  1402. if ($pos) {
  1403. $protocol = substr($protocol, $pos+1);
  1404. }
  1405. if (strlen($protocol) > 15) {
  1406. $protocol = substr($protocol, 0, 13) . '..';
  1407. }
  1408. $worker_name = isset($connection->worker) ? $connection->worker->name : $default_worker_name;
  1409. if (strlen($worker_name) > 14) {
  1410. $worker_name = substr($worker_name, 0, 12) . '..';
  1411. }
  1412. $str .= str_pad($pid, 9) . str_pad($worker_name, 16) . str_pad($id, 10) . str_pad($transport, 8)
  1413. . str_pad($protocol, 16) . str_pad($ipv4, 7) . str_pad($ipv6, 7) . str_pad($recv_q, 13)
  1414. . str_pad($send_q, 13) . str_pad($bytes_read, 13) . str_pad($bytes_written, 13) . ' '
  1415. . str_pad($state, 14) . ' ' . str_pad($local_address, 22) . ' ' . str_pad($remote_address, 22) ."\n";
  1416. }
  1417. if ($str) {
  1418. file_put_contents(self::$_statisticsFile, $str, FILE_APPEND);
  1419. }
  1420. }
  1421. /**
  1422. * Check errors when current process exited.
  1423. *
  1424. * @return void
  1425. */
  1426. public static function checkErrors()
  1427. {
  1428. if (self::STATUS_SHUTDOWN != self::$_status) {
  1429. $error_msg = 'Worker['. posix_getpid() .'] process terminated';
  1430. $errors = error_get_last();
  1431. if ($errors && ($errors['type'] === E_ERROR ||
  1432. $errors['type'] === E_PARSE ||
  1433. $errors['type'] === E_CORE_ERROR ||
  1434. $errors['type'] === E_COMPILE_ERROR ||
  1435. $errors['type'] === E_RECOVERABLE_ERROR)
  1436. ) {
  1437. $error_msg .= ' with ERROR: ' . self::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\"";
  1438. }
  1439. self::log($error_msg);
  1440. }
  1441. }
  1442. /**
  1443. * Get error message by error code.
  1444. *
  1445. * @param integer $type
  1446. * @return string
  1447. */
  1448. protected static function getErrorType($type)
  1449. {
  1450. switch ($type) {
  1451. case E_ERROR: // 1 //
  1452. return 'E_ERROR';
  1453. case E_WARNING: // 2 //
  1454. return 'E_WARNING';
  1455. case E_PARSE: // 4 //
  1456. return 'E_PARSE';
  1457. case E_NOTICE: // 8 //
  1458. return 'E_NOTICE';
  1459. case E_CORE_ERROR: // 16 //
  1460. return 'E_CORE_ERROR';
  1461. case E_CORE_WARNING: // 32 //
  1462. return 'E_CORE_WARNING';
  1463. case E_COMPILE_ERROR: // 64 //
  1464. return 'E_COMPILE_ERROR';
  1465. case E_COMPILE_WARNING: // 128 //
  1466. return 'E_COMPILE_WARNING';
  1467. case E_USER_ERROR: // 256 //
  1468. return 'E_USER_ERROR';
  1469. case E_USER_WARNING: // 512 //
  1470. return 'E_USER_WARNING';
  1471. case E_USER_NOTICE: // 1024 //
  1472. return 'E_USER_NOTICE';
  1473. case E_STRICT: // 2048 //
  1474. return 'E_STRICT';
  1475. case E_RECOVERABLE_ERROR: // 4096 //
  1476. return 'E_RECOVERABLE_ERROR';
  1477. case E_DEPRECATED: // 8192 //
  1478. return 'E_DEPRECATED';
  1479. case E_USER_DEPRECATED: // 16384 //
  1480. return 'E_USER_DEPRECATED';
  1481. }
  1482. return "";
  1483. }
  1484. /**
  1485. * Log.
  1486. *
  1487. * @param string $msg
  1488. * @return void
  1489. */
  1490. public static function log($msg)
  1491. {
  1492. $msg = $msg . "\n";
  1493. if (!self::$daemonize) {
  1494. self::safeEcho($msg);
  1495. }
  1496. file_put_contents((string)self::$logFile, date('Y-m-d H:i:s') . ' ' . 'pid:'. posix_getpid() . ' ' . $msg, FILE_APPEND | LOCK_EX);
  1497. }
  1498. /**
  1499. * Safe Echo.
  1500. *
  1501. * @param $msg
  1502. */
  1503. public static function safeEcho($msg)
  1504. {
  1505. if (!function_exists('posix_isatty') || posix_isatty(STDOUT)) {
  1506. echo $msg;
  1507. }
  1508. }
  1509. /**
  1510. * Construct.
  1511. *
  1512. * @param string $socket_name
  1513. * @param array $context_option
  1514. */
  1515. public function __construct($socket_name = '', $context_option = array())
  1516. {
  1517. // Save all worker instances.
  1518. $this->workerId = spl_object_hash($this);
  1519. self::$_workers[$this->workerId] = $this;
  1520. self::$_pidMap[$this->workerId] = array();
  1521. // Get autoload root path.
  1522. $backtrace = debug_backtrace();
  1523. $this->_autoloadRootPath = dirname($backtrace[0]['file']);
  1524. // Context for socket.
  1525. if ($socket_name) {
  1526. $this->_socketName = $socket_name;
  1527. if (!isset($context_option['socket']['backlog'])) {
  1528. $context_option['socket']['backlog'] = self::DEFAULT_BACKLOG;
  1529. }
  1530. $this->_context = stream_context_create($context_option);
  1531. }
  1532. // Set an empty onMessage callback.
  1533. $this->onMessage = function () {
  1534. };
  1535. }
  1536. /**
  1537. * Listen.
  1538. *
  1539. * @throws Exception
  1540. */
  1541. public function listen()
  1542. {
  1543. if (!$this->_socketName) {
  1544. return;
  1545. }
  1546. // Autoload.
  1547. Autoloader::setRootPath($this->_autoloadRootPath);
  1548. if (!$this->_mainSocket) {
  1549. // Get the application layer communication protocol and listening address.
  1550. list($scheme, $address) = explode(':', $this->_socketName, 2);
  1551. // Check application layer protocol class.
  1552. if (!isset(self::$_builtinTransports[$scheme])) {
  1553. $scheme = ucfirst($scheme);
  1554. $this->protocol = '\\Protocols\\' . $scheme;
  1555. if (!class_exists($this->protocol)) {
  1556. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  1557. if (!class_exists($this->protocol)) {
  1558. throw new Exception("class \\Protocols\\$scheme not exist");
  1559. }
  1560. }
  1561. if (!isset(self::$_builtinTransports[$this->transport])) {
  1562. throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
  1563. }
  1564. } else {
  1565. $this->transport = $scheme;
  1566. }
  1567. $local_socket = self::$_builtinTransports[$this->transport] . ":" . $address;
  1568. // Flag.
  1569. $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
  1570. $errno = 0;
  1571. $errmsg = '';
  1572. // SO_REUSEPORT.
  1573. if ($this->reusePort) {
  1574. stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
  1575. }
  1576. // Create an Internet or Unix domain server socket.
  1577. $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
  1578. if (!$this->_mainSocket) {
  1579. throw new Exception($errmsg);
  1580. }
  1581. if ($this->transport === 'ssl') {
  1582. stream_socket_enable_crypto($this->_mainSocket, false);
  1583. } elseif ($this->transport === 'unix') {
  1584. $socketFile = substr($address, 2);
  1585. if ($this->user) {
  1586. chown($socketFile, $this->user);
  1587. }
  1588. if ($this->group) {
  1589. chgrp($socketFile, $this->group);
  1590. }
  1591. }
  1592. // Try to open keepalive for tcp and disable Nagle algorithm.
  1593. if (function_exists('socket_import_stream') && self::$_builtinTransports[$this->transport] === 'tcp') {
  1594. $socket = socket_import_stream($this->_mainSocket);
  1595. @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  1596. @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
  1597. }
  1598. // Non blocking.
  1599. stream_set_blocking($this->_mainSocket, 0);
  1600. }
  1601. // Register a listener to be notified when server socket is ready to read.
  1602. if (self::$globalEvent || $this->_pauseListen) {
  1603. if ($this->transport !== 'udp') {
  1604. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
  1605. } else {
  1606. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1607. array($this, 'acceptUdpConnection'));
  1608. }
  1609. $this->_pauseListen = false;
  1610. }
  1611. }
  1612. /**
  1613. * Unlisten.
  1614. *
  1615. * @return void
  1616. */
  1617. public function unlisten() {
  1618. if (self::$globalEvent && $this->_mainSocket) {
  1619. self::$globalEvent->del($this->_mainSocket, EventInterface::EV_READ);
  1620. $this->_pauseListen = true;
  1621. }
  1622. }
  1623. /**
  1624. * Get socket name.
  1625. *
  1626. * @return string
  1627. */
  1628. public function getSocketName()
  1629. {
  1630. return $this->_socketName ? lcfirst($this->_socketName) : 'none';
  1631. }
  1632. /**
  1633. * Run worker instance.
  1634. *
  1635. * @return void
  1636. */
  1637. public function run()
  1638. {
  1639. //Update process state.
  1640. self::$_status = self::STATUS_RUNNING;
  1641. // Register shutdown function for checking errors.
  1642. register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));
  1643. // Set autoload root path.
  1644. Autoloader::setRootPath($this->_autoloadRootPath);
  1645. // Create a global event loop.
  1646. if (!self::$globalEvent) {
  1647. $event_loop_class = self::getEventLoopName();
  1648. self::$globalEvent = new $event_loop_class;
  1649. // Register a listener to be notified when server socket is ready to read.
  1650. if ($this->_socketName) {
  1651. if ($this->transport !== 'udp') {
  1652. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1653. array($this, 'acceptConnection'));
  1654. } else {
  1655. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1656. array($this, 'acceptUdpConnection'));
  1657. }
  1658. }
  1659. }
  1660. // Reinstall signal.
  1661. self::reinstallSignal();
  1662. // Init Timer.
  1663. Timer::init(self::$globalEvent);
  1664. // Try to emit onWorkerStart callback.
  1665. if ($this->onWorkerStart) {
  1666. try {
  1667. call_user_func($this->onWorkerStart, $this);
  1668. } catch (\Exception $e) {
  1669. self::log($e);
  1670. // Avoid rapid infinite loop exit.
  1671. sleep(1);
  1672. exit(250);
  1673. } catch (\Error $e) {
  1674. self::log($e);
  1675. // Avoid rapid infinite loop exit.
  1676. sleep(1);
  1677. exit(250);
  1678. }
  1679. }
  1680. // Main loop.
  1681. self::$globalEvent->loop();
  1682. }
  1683. /**
  1684. * Stop current worker instance.
  1685. *
  1686. * @return void
  1687. */
  1688. public function stop()
  1689. {
  1690. // Try to emit onWorkerStop callback.
  1691. if ($this->onWorkerStop) {
  1692. try {
  1693. call_user_func($this->onWorkerStop, $this);
  1694. } catch (\Exception $e) {
  1695. self::log($e);
  1696. exit(250);
  1697. } catch (\Error $e) {
  1698. self::log($e);
  1699. exit(250);
  1700. }
  1701. }
  1702. // Remove listener for server socket.
  1703. $this->unlisten();
  1704. }
  1705. /**
  1706. * Accept a connection.
  1707. *
  1708. * @param resource $socket
  1709. * @return void
  1710. */
  1711. public function acceptConnection($socket)
  1712. {
  1713. // Accept a connection on server socket.
  1714. $new_socket = @stream_socket_accept($socket, 0, $remote_address);
  1715. // Thundering herd.
  1716. if (!$new_socket) {
  1717. return;
  1718. }
  1719. // TcpConnection.
  1720. $connection = new TcpConnection($new_socket, $remote_address);
  1721. $this->connections[$connection->id] = $connection;
  1722. $connection->worker = $this;
  1723. $connection->protocol = $this->protocol;
  1724. $connection->transport = $this->transport;
  1725. $connection->onMessage = $this->onMessage;
  1726. $connection->onClose = $this->onClose;
  1727. $connection->onError = $this->onError;
  1728. $connection->onBufferDrain = $this->onBufferDrain;
  1729. $connection->onBufferFull = $this->onBufferFull;
  1730. // Try to emit onConnect callback.
  1731. if ($this->onConnect) {
  1732. try {
  1733. call_user_func($this->onConnect, $connection);
  1734. } catch (\Exception $e) {
  1735. self::log($e);
  1736. exit(250);
  1737. } catch (\Error $e) {
  1738. self::log($e);
  1739. exit(250);
  1740. }
  1741. }
  1742. }
  1743. /**
  1744. * For udp package.
  1745. *
  1746. * @param resource $socket
  1747. * @return bool
  1748. */
  1749. public function acceptUdpConnection($socket)
  1750. {
  1751. $recv_buffer = stream_socket_recvfrom($socket, self::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
  1752. if (false === $recv_buffer || empty($remote_address)) {
  1753. return false;
  1754. }
  1755. // UdpConnection.
  1756. $connection = new UdpConnection($socket, $remote_address);
  1757. $connection->protocol = $this->protocol;
  1758. if ($this->onMessage) {
  1759. if ($this->protocol !== null) {
  1760. $parser = $this->protocol;
  1761. $recv_buffer = $parser::decode($recv_buffer, $connection);
  1762. // Discard bad packets.
  1763. if ($recv_buffer === false)
  1764. return true;
  1765. }
  1766. ConnectionInterface::$statistics['total_request']++;
  1767. try {
  1768. call_user_func($this->onMessage, $connection, $recv_buffer);
  1769. } catch (\Exception $e) {
  1770. self::log($e);
  1771. exit(250);
  1772. } catch (\Error $e) {
  1773. self::log($e);
  1774. exit(250);
  1775. }
  1776. }
  1777. return true;
  1778. }
  1779. }