Worker.php 79 KB

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