Worker.php 61 KB

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