Worker.php 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  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.
  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. if (!$this->_mainSocket) {
  1487. // Get the application layer communication protocol and listening address.
  1488. list($scheme, $address) = explode(':', $this->_socketName, 2);
  1489. // Check application layer protocol class.
  1490. if (!isset(self::$_builtinTransports[$scheme])) {
  1491. $scheme = ucfirst($scheme);
  1492. $this->protocol = '\\Protocols\\' . $scheme;
  1493. if (!class_exists($this->protocol)) {
  1494. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  1495. if (!class_exists($this->protocol)) {
  1496. throw new Exception("class \\Protocols\\$scheme not exist");
  1497. }
  1498. }
  1499. if (!isset(self::$_builtinTransports[$this->transport])) {
  1500. throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
  1501. }
  1502. } else {
  1503. $this->transport = $scheme;
  1504. }
  1505. $local_socket = self::$_builtinTransports[$this->transport] . ":" . $address;
  1506. // Flag.
  1507. $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
  1508. $errno = 0;
  1509. $errmsg = '';
  1510. // SO_REUSEPORT.
  1511. if ($this->reusePort) {
  1512. stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
  1513. }
  1514. // Create an Internet or Unix domain server socket.
  1515. $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
  1516. if (!$this->_mainSocket) {
  1517. throw new Exception($errmsg);
  1518. }
  1519. if ($this->transport === 'ssl') {
  1520. stream_socket_enable_crypto($this->_mainSocket, false);
  1521. } elseif ($this->transport === 'unix') {
  1522. $socketFile = substr($address, 2);
  1523. if ($this->user) {
  1524. chown($socketFile, $this->user);
  1525. }
  1526. if ($this->group) {
  1527. chgrp($socketFile, $this->group);
  1528. }
  1529. }
  1530. // Try to open keepalive for tcp and disable Nagle algorithm.
  1531. if (function_exists('socket_import_stream') && self::$_builtinTransports[$this->transport] === 'tcp') {
  1532. $socket = socket_import_stream($this->_mainSocket);
  1533. @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  1534. @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
  1535. }
  1536. // Non blocking.
  1537. stream_set_blocking($this->_mainSocket, 0);
  1538. }
  1539. // Register a listener to be notified when server socket is ready to read.
  1540. if (self::$globalEvent) {
  1541. if ($this->transport !== 'udp') {
  1542. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
  1543. } else {
  1544. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1545. array($this, 'acceptUdpConnection'));
  1546. }
  1547. }
  1548. }
  1549. /**
  1550. * Unlisten.
  1551. *
  1552. * @return void
  1553. */
  1554. public function unlisten() {
  1555. if (self::$globalEvent && $this->_mainSocket) {
  1556. self::$globalEvent->del($this->_mainSocket, EventInterface::EV_READ);
  1557. }
  1558. }
  1559. /**
  1560. * Get socket name.
  1561. *
  1562. * @return string
  1563. */
  1564. public function getSocketName()
  1565. {
  1566. return $this->_socketName ? lcfirst($this->_socketName) : 'none';
  1567. }
  1568. /**
  1569. * Run worker instance.
  1570. *
  1571. * @return void
  1572. */
  1573. public function run()
  1574. {
  1575. //Update process state.
  1576. self::$_status = self::STATUS_RUNNING;
  1577. // Register shutdown function for checking errors.
  1578. register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));
  1579. // Set autoload root path.
  1580. Autoloader::setRootPath($this->_autoloadRootPath);
  1581. // Create a global event loop.
  1582. if (!self::$globalEvent) {
  1583. $event_loop_class = self::getEventLoopName();
  1584. self::$globalEvent = new $event_loop_class;
  1585. // Register a listener to be notified when server socket is ready to read.
  1586. if ($this->_socketName) {
  1587. if ($this->transport !== 'udp') {
  1588. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1589. array($this, 'acceptConnection'));
  1590. } else {
  1591. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1592. array($this, 'acceptUdpConnection'));
  1593. }
  1594. }
  1595. }
  1596. // Reinstall signal.
  1597. self::reinstallSignal();
  1598. // Init Timer.
  1599. Timer::init(self::$globalEvent);
  1600. // Try to emit onWorkerStart callback.
  1601. if ($this->onWorkerStart) {
  1602. try {
  1603. call_user_func($this->onWorkerStart, $this);
  1604. } catch (\Exception $e) {
  1605. self::log($e);
  1606. // Avoid rapid infinite loop exit.
  1607. sleep(1);
  1608. exit(250);
  1609. } catch (\Error $e) {
  1610. self::log($e);
  1611. // Avoid rapid infinite loop exit.
  1612. sleep(1);
  1613. exit(250);
  1614. }
  1615. }
  1616. // Main loop.
  1617. self::$globalEvent->loop();
  1618. }
  1619. /**
  1620. * Stop current worker instance.
  1621. *
  1622. * @return void
  1623. */
  1624. public function stop()
  1625. {
  1626. // Try to emit onWorkerStop callback.
  1627. if ($this->onWorkerStop) {
  1628. try {
  1629. call_user_func($this->onWorkerStop, $this);
  1630. } catch (\Exception $e) {
  1631. self::log($e);
  1632. exit(250);
  1633. } catch (\Error $e) {
  1634. self::log($e);
  1635. exit(250);
  1636. }
  1637. }
  1638. // Remove listener for server socket.
  1639. if ($this->_mainSocket) {
  1640. self::$globalEvent->del($this->_mainSocket, EventInterface::EV_READ);
  1641. @fclose($this->_mainSocket);
  1642. }
  1643. }
  1644. /**
  1645. * Accept a connection.
  1646. *
  1647. * @param resource $socket
  1648. * @return void
  1649. */
  1650. public function acceptConnection($socket)
  1651. {
  1652. // Accept a connection on server socket.
  1653. $new_socket = @stream_socket_accept($socket, 0, $remote_address);
  1654. // Thundering herd.
  1655. if (!$new_socket) {
  1656. return;
  1657. }
  1658. // TcpConnection.
  1659. $connection = new TcpConnection($new_socket, $remote_address);
  1660. $this->connections[$connection->id] = $connection;
  1661. $connection->worker = $this;
  1662. $connection->protocol = $this->protocol;
  1663. $connection->transport = $this->transport;
  1664. $connection->onMessage = $this->onMessage;
  1665. $connection->onClose = $this->onClose;
  1666. $connection->onError = $this->onError;
  1667. $connection->onBufferDrain = $this->onBufferDrain;
  1668. $connection->onBufferFull = $this->onBufferFull;
  1669. // Try to emit onConnect callback.
  1670. if ($this->onConnect) {
  1671. try {
  1672. call_user_func($this->onConnect, $connection);
  1673. } catch (\Exception $e) {
  1674. self::log($e);
  1675. exit(250);
  1676. } catch (\Error $e) {
  1677. self::log($e);
  1678. exit(250);
  1679. }
  1680. }
  1681. }
  1682. /**
  1683. * For udp package.
  1684. *
  1685. * @param resource $socket
  1686. * @return bool
  1687. */
  1688. public function acceptUdpConnection($socket)
  1689. {
  1690. $recv_buffer = stream_socket_recvfrom($socket, self::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
  1691. if (false === $recv_buffer || empty($remote_address)) {
  1692. return false;
  1693. }
  1694. // UdpConnection.
  1695. $connection = new UdpConnection($socket, $remote_address);
  1696. $connection->protocol = $this->protocol;
  1697. if ($this->onMessage) {
  1698. if ($this->protocol !== null) {
  1699. $parser = $this->protocol;
  1700. $recv_buffer = $parser::decode($recv_buffer, $connection);
  1701. // Discard bad packets.
  1702. if ($recv_buffer === false)
  1703. return true;
  1704. }
  1705. ConnectionInterface::$statistics['total_request']++;
  1706. try {
  1707. call_user_func($this->onMessage, $connection, $recv_buffer);
  1708. } catch (\Exception $e) {
  1709. self::log($e);
  1710. exit(250);
  1711. } catch (\Error $e) {
  1712. self::log($e);
  1713. exit(250);
  1714. }
  1715. }
  1716. return true;
  1717. }
  1718. }