Worker.php 58 KB

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