Worker.php 69 KB

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