Worker.php 76 KB

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