Worker.php 79 KB

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