Worker.php 80 KB

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