Worker.php 59 KB

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