Worker.php 70 KB

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