Worker.php 56 KB

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