Worker.php 78 KB

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