Worker.php 73 KB

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