Worker.php 58 KB

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