Worker.php 79 KB

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