Worker.php 78 KB

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