Worker.php 78 KB

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