Worker.php 79 KB

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