Worker.php 80 KB

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