Worker.php 58 KB

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