Worker.php 78 KB

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