Worker.php 77 KB

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