Worker.php 80 KB

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