Worker.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563
  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<[email protected]>
  10. * @copyright walkor<[email protected]>
  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.15';
  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. $argv = $_SERVER['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. $argv = $_SERVER['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_alive = $master_pid && \posix_kill($master_pid, 0) && \posix_getpid() !== $master_pid;
  803. // Master is still alive?
  804. if ($master_is_alive) {
  805. if ($command === 'start') {
  806. static::log("Workerman[$start_file] already running");
  807. exit;
  808. }
  809. } elseif ($command !== 'start' && $command !== 'restart') {
  810. static::log("Workerman[$start_file] not run");
  811. exit;
  812. }
  813. // execute command.
  814. switch ($command) {
  815. case 'start':
  816. if ($mode === '-d') {
  817. static::$daemonize = true;
  818. }
  819. break;
  820. case 'status':
  821. while (1) {
  822. if (\is_file(static::$_statisticsFile)) {
  823. @\unlink(static::$_statisticsFile);
  824. }
  825. // Master process will send SIGUSR2 signal to all child processes.
  826. \posix_kill($master_pid, SIGUSR2);
  827. // Sleep 1 second.
  828. \sleep(1);
  829. // Clear terminal.
  830. if ($mode === '-d') {
  831. static::safeEcho("\33[H\33[2J\33(B\33[m", true);
  832. }
  833. // Echo status data.
  834. static::safeEcho(static::formatStatusData());
  835. if ($mode !== '-d') {
  836. exit(0);
  837. }
  838. static::safeEcho("\nPress Ctrl+C to quit.\n\n");
  839. }
  840. exit(0);
  841. case 'connections':
  842. if (\is_file(static::$_statisticsFile) && \is_writable(static::$_statisticsFile)) {
  843. \unlink(static::$_statisticsFile);
  844. }
  845. // Master process will send SIGIO signal to all child processes.
  846. \posix_kill($master_pid, SIGIO);
  847. // Waiting amoment.
  848. \usleep(500000);
  849. // Display statisitcs data from a disk file.
  850. if(\is_readable(static::$_statisticsFile)) {
  851. \readfile(static::$_statisticsFile);
  852. }
  853. exit(0);
  854. case 'restart':
  855. case 'stop':
  856. if ($mode === '-g') {
  857. static::$_gracefulStop = true;
  858. $sig = \SIGHUP;
  859. static::log("Workerman[$start_file] is gracefully stopping ...");
  860. } else {
  861. static::$_gracefulStop = false;
  862. $sig = \SIGINT;
  863. static::log("Workerman[$start_file] is stopping ...");
  864. }
  865. // Send stop signal to master process.
  866. $master_pid && \posix_kill($master_pid, $sig);
  867. // Timeout.
  868. $timeout = 5;
  869. $start_time = \time();
  870. // Check master process is still alive?
  871. while (1) {
  872. $master_is_alive = $master_pid && \posix_kill($master_pid, 0);
  873. if ($master_is_alive) {
  874. // Timeout?
  875. if (!static::$_gracefulStop && \time() - $start_time >= $timeout) {
  876. static::log("Workerman[$start_file] stop fail");
  877. exit;
  878. }
  879. // Waiting amoment.
  880. \usleep(10000);
  881. continue;
  882. }
  883. // Stop success.
  884. static::log("Workerman[$start_file] stop success");
  885. if ($command === 'stop') {
  886. exit(0);
  887. }
  888. if ($mode === '-d') {
  889. static::$daemonize = true;
  890. }
  891. break;
  892. }
  893. break;
  894. case 'reload':
  895. if($mode === '-g'){
  896. $sig = \SIGQUIT;
  897. }else{
  898. $sig = \SIGUSR1;
  899. }
  900. \posix_kill($master_pid, $sig);
  901. exit;
  902. default :
  903. if (isset($command)) {
  904. static::safeEcho('Unknown command: ' . $command . "\n");
  905. }
  906. exit($usage);
  907. }
  908. }
  909. /**
  910. * Format status data.
  911. *
  912. * @return string
  913. */
  914. protected static function formatStatusData()
  915. {
  916. static $total_request_cache = array();
  917. if (!\is_readable(static::$_statisticsFile)) {
  918. return '';
  919. }
  920. $info = \file(static::$_statisticsFile, \FILE_IGNORE_NEW_LINES);
  921. if (!$info) {
  922. return '';
  923. }
  924. $status_str = '';
  925. $current_total_request = array();
  926. $worker_info = \unserialize($info[0]);
  927. \ksort($worker_info, SORT_NUMERIC);
  928. unset($info[0]);
  929. $data_waiting_sort = array();
  930. $read_process_status = false;
  931. $total_requests = 0;
  932. $total_qps = 0;
  933. $total_connections = 0;
  934. $total_fails = 0;
  935. $total_memory = 0;
  936. $total_timers = 0;
  937. $maxLen1 = static::$_maxSocketNameLength;
  938. $maxLen2 = static::$_maxWorkerNameLength;
  939. foreach($info as $key => $value) {
  940. if (!$read_process_status) {
  941. $status_str .= $value . "\n";
  942. if (\preg_match('/^pid.*?memory.*?listening/', $value)) {
  943. $read_process_status = true;
  944. }
  945. continue;
  946. }
  947. if(\preg_match('/^[0-9]+/', $value, $pid_math)) {
  948. $pid = $pid_math[0];
  949. $data_waiting_sort[$pid] = $value;
  950. if(\preg_match('/^\S+?\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?/', $value, $match)) {
  951. $total_memory += \intval(\str_ireplace('M','',$match[1]));
  952. $maxLen1 = \max($maxLen1,\strlen($match[2]));
  953. $maxLen2 = \max($maxLen2,\strlen($match[3]));
  954. $total_connections += \intval($match[4]);
  955. $total_fails += \intval($match[5]);
  956. $total_timers += \intval($match[6]);
  957. $current_total_request[$pid] = $match[7];
  958. $total_requests += \intval($match[7]);
  959. }
  960. }
  961. }
  962. foreach($worker_info as $pid => $info) {
  963. if (!isset($data_waiting_sort[$pid])) {
  964. $status_str .= "$pid\t" . \str_pad('N/A', 7) . " "
  965. . \str_pad($info['listen'], static::$_maxSocketNameLength) . " "
  966. . \str_pad($info['name'], static::$_maxWorkerNameLength) . " "
  967. . \str_pad('N/A', 11) . " " . \str_pad('N/A', 9) . " "
  968. . \str_pad('N/A', 7) . " " . \str_pad('N/A', 13) . " N/A [busy] \n";
  969. continue;
  970. }
  971. //$qps = isset($total_request_cache[$pid]) ? $current_total_request[$pid]
  972. if (!isset($total_request_cache[$pid]) || !isset($current_total_request[$pid])) {
  973. $qps = 0;
  974. } else {
  975. $qps = $current_total_request[$pid] - $total_request_cache[$pid];
  976. $total_qps += $qps;
  977. }
  978. $status_str .= $data_waiting_sort[$pid]. " " . \str_pad($qps, 6) ." [idle]\n";
  979. }
  980. $total_request_cache = $current_total_request;
  981. $status_str .= "----------------------------------------------PROCESS STATUS---------------------------------------------------\n";
  982. $status_str .= "Summary\t" . \str_pad($total_memory.'M', 7) . " "
  983. . \str_pad('-', $maxLen1) . " "
  984. . \str_pad('-', $maxLen2) . " "
  985. . \str_pad($total_connections, 11) . " " . \str_pad($total_fails, 9) . " "
  986. . \str_pad($total_timers, 7) . " " . \str_pad($total_requests, 13) . " "
  987. . \str_pad($total_qps,6)." [Summary] \n";
  988. return $status_str;
  989. }
  990. /**
  991. * Install signal handler.
  992. *
  993. * @return void
  994. */
  995. protected static function installSignal()
  996. {
  997. if (static::$_OS !== \OS_TYPE_LINUX) {
  998. return;
  999. }
  1000. $signalHandler = '\Workerman\Worker::signalHandler';
  1001. // stop
  1002. \pcntl_signal(\SIGINT, $signalHandler, false);
  1003. // stop
  1004. \pcntl_signal(\SIGTERM, $signalHandler, false);
  1005. // graceful stop
  1006. \pcntl_signal(\SIGHUP, $signalHandler, false);
  1007. // reload
  1008. \pcntl_signal(\SIGUSR1, $signalHandler, false);
  1009. // graceful reload
  1010. \pcntl_signal(\SIGQUIT, $signalHandler, false);
  1011. // status
  1012. \pcntl_signal(\SIGUSR2, $signalHandler, false);
  1013. // connection status
  1014. \pcntl_signal(\SIGIO, $signalHandler, false);
  1015. // ignore
  1016. \pcntl_signal(\SIGPIPE, \SIG_IGN, false);
  1017. }
  1018. /**
  1019. * Reinstall signal handler.
  1020. *
  1021. * @return void
  1022. */
  1023. protected static function reinstallSignal()
  1024. {
  1025. if (static::$_OS !== \OS_TYPE_LINUX) {
  1026. return;
  1027. }
  1028. $signalHandler = '\Workerman\Worker::signalHandler';
  1029. // uninstall stop signal handler
  1030. \pcntl_signal(\SIGINT, \SIG_IGN, false);
  1031. // uninstall stop signal handler
  1032. \pcntl_signal(\SIGTERM, \SIG_IGN, false);
  1033. // uninstall graceful stop signal handler
  1034. \pcntl_signal(\SIGHUP, \SIG_IGN, false);
  1035. // uninstall reload signal handler
  1036. \pcntl_signal(\SIGUSR1, \SIG_IGN, false);
  1037. // uninstall graceful reload signal handler
  1038. \pcntl_signal(\SIGQUIT, \SIG_IGN, false);
  1039. // uninstall status signal handler
  1040. \pcntl_signal(\SIGUSR2, \SIG_IGN, false);
  1041. // uninstall connections status signal handler
  1042. \pcntl_signal(\SIGIO, \SIG_IGN, false);
  1043. // reinstall stop signal handler
  1044. static::$globalEvent->add(\SIGINT, EventInterface::EV_SIGNAL, $signalHandler);
  1045. // reinstall graceful stop signal handler
  1046. static::$globalEvent->add(\SIGHUP, EventInterface::EV_SIGNAL, $signalHandler);
  1047. // reinstall reload signal handler
  1048. static::$globalEvent->add(\SIGUSR1, EventInterface::EV_SIGNAL, $signalHandler);
  1049. // reinstall graceful reload signal handler
  1050. static::$globalEvent->add(\SIGQUIT, EventInterface::EV_SIGNAL, $signalHandler);
  1051. // reinstall status signal handler
  1052. static::$globalEvent->add(\SIGUSR2, EventInterface::EV_SIGNAL, $signalHandler);
  1053. // reinstall connection status signal handler
  1054. static::$globalEvent->add(\SIGIO, EventInterface::EV_SIGNAL, $signalHandler);
  1055. }
  1056. /**
  1057. * Signal handler.
  1058. *
  1059. * @param int $signal
  1060. */
  1061. public static function signalHandler($signal)
  1062. {
  1063. switch ($signal) {
  1064. // Stop.
  1065. case \SIGINT:
  1066. case \SIGTERM:
  1067. static::$_gracefulStop = false;
  1068. static::stopAll();
  1069. break;
  1070. // Graceful stop.
  1071. case \SIGHUP:
  1072. static::$_gracefulStop = true;
  1073. static::stopAll();
  1074. break;
  1075. // Reload.
  1076. case \SIGQUIT:
  1077. case \SIGUSR1:
  1078. static::$_gracefulStop = $signal === \SIGQUIT;
  1079. static::$_pidsToRestart = static::getAllWorkerPids();
  1080. static::reload();
  1081. break;
  1082. // Show status.
  1083. case \SIGUSR2:
  1084. static::writeStatisticsToStatusFile();
  1085. break;
  1086. // Show connection status.
  1087. case \SIGIO:
  1088. static::writeConnectionsStatisticsToStatusFile();
  1089. break;
  1090. }
  1091. }
  1092. /**
  1093. * Run as deamon mode.
  1094. *
  1095. * @throws Exception
  1096. */
  1097. protected static function daemonize()
  1098. {
  1099. if (!static::$daemonize || static::$_OS !== \OS_TYPE_LINUX) {
  1100. return;
  1101. }
  1102. \umask(0);
  1103. $pid = \pcntl_fork();
  1104. if (-1 === $pid) {
  1105. throw new Exception('Fork fail');
  1106. } elseif ($pid > 0) {
  1107. exit(0);
  1108. }
  1109. if (-1 === \posix_setsid()) {
  1110. throw new Exception("Setsid fail");
  1111. }
  1112. // Fork again avoid SVR4 system regain the control of terminal.
  1113. $pid = \pcntl_fork();
  1114. if (-1 === $pid) {
  1115. throw new Exception("Fork fail");
  1116. } elseif (0 !== $pid) {
  1117. exit(0);
  1118. }
  1119. }
  1120. /**
  1121. * Redirect standard input and output.
  1122. *
  1123. * @throws Exception
  1124. */
  1125. public static function resetStd()
  1126. {
  1127. if (!static::$daemonize || static::$_OS !== \OS_TYPE_LINUX) {
  1128. return;
  1129. }
  1130. global $STDOUT, $STDERR;
  1131. $handle = \fopen(static::$stdoutFile, "a");
  1132. if ($handle) {
  1133. unset($handle);
  1134. \set_error_handler(function(){});
  1135. if ($STDOUT) {
  1136. \fclose($STDOUT);
  1137. }
  1138. if ($STDERR) {
  1139. \fclose($STDERR);
  1140. }
  1141. \fclose(\STDOUT);
  1142. \fclose(\STDERR);
  1143. $STDOUT = \fopen(static::$stdoutFile, "a");
  1144. $STDERR = \fopen(static::$stdoutFile, "a");
  1145. // change output stream
  1146. static::$_outputStream = null;
  1147. static::outputStream($STDOUT);
  1148. \restore_error_handler();
  1149. return;
  1150. }
  1151. throw new Exception('Can not open stdoutFile ' . static::$stdoutFile);
  1152. }
  1153. /**
  1154. * Save pid.
  1155. *
  1156. * @throws Exception
  1157. */
  1158. protected static function saveMasterPid()
  1159. {
  1160. if (static::$_OS !== \OS_TYPE_LINUX) {
  1161. return;
  1162. }
  1163. static::$_masterPid = \posix_getpid();
  1164. if (false === \file_put_contents(static::$pidFile, static::$_masterPid)) {
  1165. throw new Exception('can not save pid to ' . static::$pidFile);
  1166. }
  1167. }
  1168. /**
  1169. * Get event loop name.
  1170. *
  1171. * @return string
  1172. */
  1173. protected static function getEventLoopName()
  1174. {
  1175. if (static::$eventLoopClass) {
  1176. return static::$eventLoopClass;
  1177. }
  1178. if (!\class_exists('\Swoole\Event', false)) {
  1179. unset(static::$_availableEventLoops['swoole']);
  1180. }
  1181. $loop_name = '';
  1182. foreach (static::$_availableEventLoops as $name=>$class) {
  1183. if (\extension_loaded($name)) {
  1184. $loop_name = $name;
  1185. break;
  1186. }
  1187. }
  1188. if ($loop_name) {
  1189. if (\interface_exists('\React\EventLoop\LoopInterface')) {
  1190. switch ($loop_name) {
  1191. case 'libevent':
  1192. static::$eventLoopClass = '\Workerman\Events\React\ExtLibEventLoop';
  1193. break;
  1194. case 'event':
  1195. static::$eventLoopClass = '\Workerman\Events\React\ExtEventLoop';
  1196. break;
  1197. default :
  1198. static::$eventLoopClass = '\Workerman\Events\React\StreamSelectLoop';
  1199. break;
  1200. }
  1201. } else {
  1202. static::$eventLoopClass = static::$_availableEventLoops[$loop_name];
  1203. }
  1204. } else {
  1205. static::$eventLoopClass = \interface_exists('\React\EventLoop\LoopInterface') ? '\Workerman\Events\React\StreamSelectLoop' : '\Workerman\Events\Select';
  1206. }
  1207. return static::$eventLoopClass;
  1208. }
  1209. /**
  1210. * Get all pids of worker processes.
  1211. *
  1212. * @return array
  1213. */
  1214. protected static function getAllWorkerPids()
  1215. {
  1216. $pid_array = array();
  1217. foreach (static::$_pidMap as $worker_pid_array) {
  1218. foreach ($worker_pid_array as $worker_pid) {
  1219. $pid_array[$worker_pid] = $worker_pid;
  1220. }
  1221. }
  1222. return $pid_array;
  1223. }
  1224. /**
  1225. * Fork some worker processes.
  1226. *
  1227. * @return void
  1228. */
  1229. protected static function forkWorkers()
  1230. {
  1231. if (static::$_OS === \OS_TYPE_LINUX) {
  1232. static::forkWorkersForLinux();
  1233. } else {
  1234. static::forkWorkersForWindows();
  1235. }
  1236. }
  1237. /**
  1238. * Fork some worker processes.
  1239. *
  1240. * @return void
  1241. */
  1242. protected static function forkWorkersForLinux()
  1243. {
  1244. foreach (static::$_workers as $worker) {
  1245. if (static::$_status === static::STATUS_STARTING) {
  1246. if (empty($worker->name)) {
  1247. $worker->name = $worker->getSocketName();
  1248. }
  1249. $worker_name_length = \strlen($worker->name);
  1250. if (static::$_maxWorkerNameLength < $worker_name_length) {
  1251. static::$_maxWorkerNameLength = $worker_name_length;
  1252. }
  1253. }
  1254. while (\count(static::$_pidMap[$worker->workerId]) < $worker->count) {
  1255. static::forkOneWorkerForLinux($worker);
  1256. }
  1257. }
  1258. }
  1259. /**
  1260. * Fork some worker processes.
  1261. *
  1262. * @return void
  1263. */
  1264. protected static function forkWorkersForWindows()
  1265. {
  1266. $files = static::getStartFilesForWindows();
  1267. global $argv;
  1268. if(\in_array('-q', $argv) || \count($files) === 1)
  1269. {
  1270. if(\count(static::$_workers) > 1)
  1271. {
  1272. static::safeEcho("@@@ Error: multi workers init in one php file are not support @@@\r\n");
  1273. static::safeEcho("@@@ See http://doc.workerman.net/faq/multi-woker-for-windows.html @@@\r\n");
  1274. }
  1275. elseif(\count(static::$_workers) <= 0)
  1276. {
  1277. exit("@@@no worker inited@@@\r\n\r\n");
  1278. }
  1279. \reset(static::$_workers);
  1280. /** @var Worker $worker */
  1281. $worker = current(static::$_workers);
  1282. // Display UI.
  1283. static::safeEcho(\str_pad($worker->name, 21) . \str_pad($worker->getSocketName(), 36) . \str_pad($worker->count, 10) . "[ok]\n");
  1284. $worker->listen();
  1285. $worker->run();
  1286. exit("@@@child exit@@@\r\n");
  1287. }
  1288. else
  1289. {
  1290. static::$globalEvent = new \Workerman\Events\Select();
  1291. Timer::init(static::$globalEvent);
  1292. foreach($files as $start_file)
  1293. {
  1294. static::forkOneWorkerForWindows($start_file);
  1295. }
  1296. }
  1297. }
  1298. /**
  1299. * Get start files for windows.
  1300. *
  1301. * @return array
  1302. */
  1303. public static function getStartFilesForWindows() {
  1304. global $argv;
  1305. $files = array();
  1306. foreach($argv as $file)
  1307. {
  1308. if(\is_file($file))
  1309. {
  1310. $files[$file] = $file;
  1311. }
  1312. }
  1313. return $files;
  1314. }
  1315. /**
  1316. * Fork one worker process.
  1317. *
  1318. * @param string $start_file
  1319. */
  1320. public static function forkOneWorkerForWindows($start_file)
  1321. {
  1322. $start_file = \realpath($start_file);
  1323. $std_file = \sys_get_temp_dir() . '/'.\str_replace(array('/', "\\", ':'), '_', $start_file).'.out.txt';
  1324. $descriptorspec = array(
  1325. 0 => array('pipe', 'a'), // stdin
  1326. 1 => array('file', $std_file, 'w'), // stdout
  1327. 2 => array('file', $std_file, 'w') // stderr
  1328. );
  1329. $pipes = array();
  1330. $process = \proc_open("php \"$start_file\" -q", $descriptorspec, $pipes);
  1331. $std_handler = \fopen($std_file, 'a+');
  1332. \stream_set_blocking($std_handler, false);
  1333. if (empty(static::$globalEvent)) {
  1334. static::$globalEvent = new Select();
  1335. Timer::init(static::$globalEvent);
  1336. }
  1337. $timer_id = Timer::add(0.1, function()use($std_handler)
  1338. {
  1339. Worker::safeEcho(\fread($std_handler, 65535));
  1340. });
  1341. // 保存子进程句柄
  1342. static::$_processForWindows[$start_file] = array($process, $start_file, $timer_id);
  1343. }
  1344. /**
  1345. * check worker status for windows.
  1346. * @return void
  1347. */
  1348. public static function checkWorkerStatusForWindows()
  1349. {
  1350. foreach(static::$_processForWindows as $process_data)
  1351. {
  1352. $process = $process_data[0];
  1353. $start_file = $process_data[1];
  1354. $timer_id = $process_data[2];
  1355. $status = \proc_get_status($process);
  1356. if(isset($status['running']))
  1357. {
  1358. if(!$status['running'])
  1359. {
  1360. static::safeEcho("process $start_file terminated and try to restart\n");
  1361. Timer::del($timer_id);
  1362. \proc_close($process);
  1363. static::forkOneWorkerForWindows($start_file);
  1364. }
  1365. }
  1366. else
  1367. {
  1368. static::safeEcho("proc_get_status fail\n");
  1369. }
  1370. }
  1371. }
  1372. /**
  1373. * Fork one worker process.
  1374. *
  1375. * @param self $worker
  1376. * @throws Exception
  1377. */
  1378. protected static function forkOneWorkerForLinux(self $worker)
  1379. {
  1380. // Get available worker id.
  1381. $id = static::getId($worker->workerId, 0);
  1382. if ($id === false) {
  1383. return;
  1384. }
  1385. $pid = \pcntl_fork();
  1386. // For master process.
  1387. if ($pid > 0) {
  1388. static::$_pidMap[$worker->workerId][$pid] = $pid;
  1389. static::$_idMap[$worker->workerId][$id] = $pid;
  1390. } // For child processes.
  1391. elseif (0 === $pid) {
  1392. \srand();
  1393. \mt_srand();
  1394. if ($worker->reusePort) {
  1395. $worker->listen();
  1396. }
  1397. if (static::$_status === static::STATUS_STARTING) {
  1398. static::resetStd();
  1399. }
  1400. static::$_pidMap = array();
  1401. // Remove other listener.
  1402. foreach(static::$_workers as $key => $one_worker) {
  1403. if ($one_worker->workerId !== $worker->workerId) {
  1404. $one_worker->unlisten();
  1405. unset(static::$_workers[$key]);
  1406. }
  1407. }
  1408. Timer::delAll();
  1409. static::setProcessTitle(self::$processTitle . ': worker process ' . $worker->name . ' ' . $worker->getSocketName());
  1410. $worker->setUserAndGroup();
  1411. $worker->id = $id;
  1412. $worker->run();
  1413. if (strpos(static::$eventLoopClass, 'Workerman\Events\Swoole') !== false) {
  1414. exit(0);
  1415. }
  1416. $err = new Exception('event-loop exited');
  1417. static::log($err);
  1418. exit(250);
  1419. } else {
  1420. throw new Exception("forkOneWorker fail");
  1421. }
  1422. }
  1423. /**
  1424. * Get worker id.
  1425. *
  1426. * @param int $worker_id
  1427. * @param int $pid
  1428. *
  1429. * @return integer
  1430. */
  1431. protected static function getId($worker_id, $pid)
  1432. {
  1433. return \array_search($pid, static::$_idMap[$worker_id]);
  1434. }
  1435. /**
  1436. * Set unix user and group for current process.
  1437. *
  1438. * @return void
  1439. */
  1440. public function setUserAndGroup()
  1441. {
  1442. // Get uid.
  1443. $user_info = \posix_getpwnam($this->user);
  1444. if (!$user_info) {
  1445. static::log("Warning: User {$this->user} not exsits");
  1446. return;
  1447. }
  1448. $uid = $user_info['uid'];
  1449. // Get gid.
  1450. if ($this->group) {
  1451. $group_info = \posix_getgrnam($this->group);
  1452. if (!$group_info) {
  1453. static::log("Warning: Group {$this->group} not exsits");
  1454. return;
  1455. }
  1456. $gid = $group_info['gid'];
  1457. } else {
  1458. $gid = $user_info['gid'];
  1459. }
  1460. // Set uid and gid.
  1461. if ($uid !== \posix_getuid() || $gid !== \posix_getgid()) {
  1462. if (!\posix_setgid($gid) || !\posix_initgroups($user_info['name'], $gid) || !\posix_setuid($uid)) {
  1463. static::log("Warning: change gid or uid fail.");
  1464. }
  1465. }
  1466. }
  1467. /**
  1468. * Set process name.
  1469. *
  1470. * @param string $title
  1471. * @return void
  1472. */
  1473. protected static function setProcessTitle($title)
  1474. {
  1475. \set_error_handler(function(){});
  1476. // >=php 5.5
  1477. if (\function_exists('cli_set_process_title')) {
  1478. \cli_set_process_title($title);
  1479. } // Need proctitle when php<=5.5 .
  1480. elseif (\extension_loaded('proctitle') && \function_exists('setproctitle')) {
  1481. \setproctitle($title);
  1482. }
  1483. \restore_error_handler();
  1484. }
  1485. /**
  1486. * Monitor all child processes.
  1487. *
  1488. * @return void
  1489. */
  1490. protected static function monitorWorkers()
  1491. {
  1492. if (static::$_OS === \OS_TYPE_LINUX) {
  1493. static::monitorWorkersForLinux();
  1494. } else {
  1495. static::monitorWorkersForWindows();
  1496. }
  1497. }
  1498. /**
  1499. * Monitor all child processes.
  1500. *
  1501. * @return void
  1502. */
  1503. protected static function monitorWorkersForLinux()
  1504. {
  1505. static::$_status = static::STATUS_RUNNING;
  1506. while (1) {
  1507. // Calls signal handlers for pending signals.
  1508. \pcntl_signal_dispatch();
  1509. // Suspends execution of the current process until a child has exited, or until a signal is delivered
  1510. $status = 0;
  1511. $pid = \pcntl_wait($status, \WUNTRACED);
  1512. // Calls signal handlers for pending signals again.
  1513. \pcntl_signal_dispatch();
  1514. // If a child has already exited.
  1515. if ($pid > 0) {
  1516. // Find out which worker process exited.
  1517. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1518. if (isset($worker_pid_array[$pid])) {
  1519. $worker = static::$_workers[$worker_id];
  1520. // Exit status.
  1521. if ($status !== 0) {
  1522. static::log("worker[" . $worker->name . ":$pid] exit with status $status");
  1523. }
  1524. // For Statistics.
  1525. if (!isset(static::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
  1526. static::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;
  1527. }
  1528. ++static::$_globalStatistics['worker_exit_info'][$worker_id][$status];
  1529. // Clear process data.
  1530. unset(static::$_pidMap[$worker_id][$pid]);
  1531. // Mark id is available.
  1532. $id = static::getId($worker_id, $pid);
  1533. static::$_idMap[$worker_id][$id] = 0;
  1534. break;
  1535. }
  1536. }
  1537. // Is still running state then fork a new worker process.
  1538. if (static::$_status !== static::STATUS_SHUTDOWN) {
  1539. static::forkWorkers();
  1540. // If reloading continue.
  1541. if (isset(static::$_pidsToRestart[$pid])) {
  1542. unset(static::$_pidsToRestart[$pid]);
  1543. static::reload();
  1544. }
  1545. }
  1546. }
  1547. // If shutdown state and all child processes exited then master process exit.
  1548. if (static::$_status === static::STATUS_SHUTDOWN && !static::getAllWorkerPids()) {
  1549. static::exitAndClearAll();
  1550. }
  1551. }
  1552. }
  1553. /**
  1554. * Monitor all child processes.
  1555. *
  1556. * @return void
  1557. */
  1558. protected static function monitorWorkersForWindows()
  1559. {
  1560. Timer::add(1, "\\Workerman\\Worker::checkWorkerStatusForWindows");
  1561. static::$globalEvent->loop();
  1562. }
  1563. /**
  1564. * Exit current process.
  1565. *
  1566. * @return void
  1567. */
  1568. protected static function exitAndClearAll()
  1569. {
  1570. foreach (static::$_workers as $worker) {
  1571. $socket_name = $worker->getSocketName();
  1572. if ($worker->transport === 'unix' && $socket_name) {
  1573. list(, $address) = \explode(':', $socket_name, 2);
  1574. @\unlink($address);
  1575. }
  1576. }
  1577. @\unlink(static::$pidFile);
  1578. static::log("Workerman[" . \basename(static::$_startFile) . "] has been stopped");
  1579. if (static::$onMasterStop) {
  1580. \call_user_func(static::$onMasterStop);
  1581. }
  1582. exit(0);
  1583. }
  1584. /**
  1585. * Execute reload.
  1586. *
  1587. * @return void
  1588. */
  1589. protected static function reload()
  1590. {
  1591. // For master process.
  1592. if (static::$_masterPid === \posix_getpid()) {
  1593. // Set reloading state.
  1594. if (static::$_status !== static::STATUS_RELOADING && static::$_status !== static::STATUS_SHUTDOWN) {
  1595. static::log("Workerman[" . \basename(static::$_startFile) . "] reloading");
  1596. static::$_status = static::STATUS_RELOADING;
  1597. // Try to emit onMasterReload callback.
  1598. if (static::$onMasterReload) {
  1599. try {
  1600. \call_user_func(static::$onMasterReload);
  1601. } catch (\Exception $e) {
  1602. static::log($e);
  1603. exit(250);
  1604. } catch (\Error $e) {
  1605. static::log($e);
  1606. exit(250);
  1607. }
  1608. static::initId();
  1609. }
  1610. }
  1611. if (static::$_gracefulStop) {
  1612. $sig = \SIGQUIT;
  1613. } else {
  1614. $sig = \SIGUSR1;
  1615. }
  1616. // Send reload signal to all child processes.
  1617. $reloadable_pid_array = array();
  1618. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1619. $worker = static::$_workers[$worker_id];
  1620. if ($worker->reloadable) {
  1621. foreach ($worker_pid_array as $pid) {
  1622. $reloadable_pid_array[$pid] = $pid;
  1623. }
  1624. } else {
  1625. foreach ($worker_pid_array as $pid) {
  1626. // Send reload signal to a worker process which reloadable is false.
  1627. \posix_kill($pid, $sig);
  1628. }
  1629. }
  1630. }
  1631. // Get all pids that are waiting reload.
  1632. static::$_pidsToRestart = \array_intersect(static::$_pidsToRestart, $reloadable_pid_array);
  1633. // Reload complete.
  1634. if (empty(static::$_pidsToRestart)) {
  1635. if (static::$_status !== static::STATUS_SHUTDOWN) {
  1636. static::$_status = static::STATUS_RUNNING;
  1637. }
  1638. return;
  1639. }
  1640. // Continue reload.
  1641. $one_worker_pid = \current(static::$_pidsToRestart);
  1642. // Send reload signal to a worker process.
  1643. \posix_kill($one_worker_pid, $sig);
  1644. // If the process does not exit after static::KILL_WORKER_TIMER_TIME seconds try to kill it.
  1645. if(!static::$_gracefulStop){
  1646. Timer::add(static::KILL_WORKER_TIMER_TIME, '\posix_kill', array($one_worker_pid, \SIGKILL), false);
  1647. }
  1648. } // For child processes.
  1649. else {
  1650. \reset(static::$_workers);
  1651. $worker = \current(static::$_workers);
  1652. // Try to emit onWorkerReload callback.
  1653. if ($worker->onWorkerReload) {
  1654. try {
  1655. \call_user_func($worker->onWorkerReload, $worker);
  1656. } catch (\Exception $e) {
  1657. static::log($e);
  1658. exit(250);
  1659. } catch (\Error $e) {
  1660. static::log($e);
  1661. exit(250);
  1662. }
  1663. }
  1664. if ($worker->reloadable) {
  1665. static::stopAll();
  1666. }
  1667. }
  1668. }
  1669. /**
  1670. * Stop.
  1671. *
  1672. * @return void
  1673. */
  1674. public static function stopAll()
  1675. {
  1676. static::$_status = static::STATUS_SHUTDOWN;
  1677. // For master process.
  1678. if (static::$_masterPid === \posix_getpid()) {
  1679. static::log("Workerman[" . \basename(static::$_startFile) . "] stopping ...");
  1680. $worker_pid_array = static::getAllWorkerPids();
  1681. // Send stop signal to all child processes.
  1682. if (static::$_gracefulStop) {
  1683. $sig = \SIGHUP;
  1684. } else {
  1685. $sig = \SIGINT;
  1686. }
  1687. foreach ($worker_pid_array as $worker_pid) {
  1688. \posix_kill($worker_pid, $sig);
  1689. if(!static::$_gracefulStop){
  1690. Timer::add(static::KILL_WORKER_TIMER_TIME, '\posix_kill', array($worker_pid, \SIGKILL), false);
  1691. }
  1692. }
  1693. Timer::add(1, "\\Workerman\\Worker::checkIfChildRunning");
  1694. // Remove statistics file.
  1695. if (\is_file(static::$_statisticsFile)) {
  1696. @\unlink(static::$_statisticsFile);
  1697. }
  1698. } // For child processes.
  1699. else {
  1700. // Execute exit.
  1701. foreach (static::$_workers as $worker) {
  1702. if(!$worker->stopping){
  1703. $worker->stop();
  1704. $worker->stopping = true;
  1705. }
  1706. }
  1707. if (!static::$_gracefulStop || ConnectionInterface::$statistics['connection_count'] <= 0) {
  1708. static::$_workers = array();
  1709. if (static::$globalEvent) {
  1710. static::$globalEvent->destroy();
  1711. }
  1712. try {
  1713. exit(0);
  1714. } catch (Exception $e) {
  1715. }
  1716. }
  1717. }
  1718. }
  1719. /**
  1720. * check if child processes is really running
  1721. */
  1722. public static function checkIfChildRunning()
  1723. {
  1724. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1725. foreach ($worker_pid_array as $pid => $worker_pid) {
  1726. if (!\posix_kill($pid, 0)) {
  1727. unset(static::$_pidMap[$worker_id][$pid]);
  1728. }
  1729. }
  1730. }
  1731. }
  1732. /**
  1733. * Get process status.
  1734. *
  1735. * @return number
  1736. */
  1737. public static function getStatus()
  1738. {
  1739. return static::$_status;
  1740. }
  1741. /**
  1742. * If stop gracefully.
  1743. *
  1744. * @return bool
  1745. */
  1746. public static function getGracefulStop()
  1747. {
  1748. return static::$_gracefulStop;
  1749. }
  1750. /**
  1751. * Write statistics data to disk.
  1752. *
  1753. * @return void
  1754. */
  1755. protected static function writeStatisticsToStatusFile()
  1756. {
  1757. // For master process.
  1758. if (static::$_masterPid === \posix_getpid()) {
  1759. $all_worker_info = array();
  1760. foreach(static::$_pidMap as $worker_id => $pid_array) {
  1761. /** @var /Workerman/Worker $worker */
  1762. $worker = static::$_workers[$worker_id];
  1763. foreach($pid_array as $pid) {
  1764. $all_worker_info[$pid] = array('name' => $worker->name, 'listen' => $worker->getSocketName());
  1765. }
  1766. }
  1767. \file_put_contents(static::$_statisticsFile, \serialize($all_worker_info)."\n", \FILE_APPEND);
  1768. $loadavg = \function_exists('sys_getloadavg') ? \array_map('round', \sys_getloadavg(), array(2)) : array('-', '-', '-');
  1769. \file_put_contents(static::$_statisticsFile,
  1770. "----------------------------------------------GLOBAL STATUS----------------------------------------------------\n", \FILE_APPEND);
  1771. \file_put_contents(static::$_statisticsFile,
  1772. 'Workerman version:' . static::VERSION . " PHP version:" . \PHP_VERSION . "\n", \FILE_APPEND);
  1773. \file_put_contents(static::$_statisticsFile, 'start time:' . \date('Y-m-d H:i:s',
  1774. 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",
  1775. FILE_APPEND);
  1776. $load_str = 'load average: ' . \implode(", ", $loadavg);
  1777. \file_put_contents(static::$_statisticsFile,
  1778. \str_pad($load_str, 33) . 'event-loop:' . static::getEventLoopName() . "\n", \FILE_APPEND);
  1779. \file_put_contents(static::$_statisticsFile,
  1780. \count(static::$_pidMap) . ' workers ' . \count(static::getAllWorkerPids()) . " processes\n",
  1781. \FILE_APPEND);
  1782. \file_put_contents(static::$_statisticsFile,
  1783. \str_pad('worker_name', static::$_maxWorkerNameLength) . " exit_status exit_count\n", \FILE_APPEND);
  1784. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1785. $worker = static::$_workers[$worker_id];
  1786. if (isset(static::$_globalStatistics['worker_exit_info'][$worker_id])) {
  1787. foreach (static::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
  1788. \file_put_contents(static::$_statisticsFile,
  1789. \str_pad($worker->name, static::$_maxWorkerNameLength) . " " . \str_pad($worker_exit_status,
  1790. 16) . " $worker_exit_count\n", \FILE_APPEND);
  1791. }
  1792. } else {
  1793. \file_put_contents(static::$_statisticsFile,
  1794. \str_pad($worker->name, static::$_maxWorkerNameLength) . " " . \str_pad(0, 16) . " 0\n",
  1795. \FILE_APPEND);
  1796. }
  1797. }
  1798. \file_put_contents(static::$_statisticsFile,
  1799. "----------------------------------------------PROCESS STATUS---------------------------------------------------\n",
  1800. \FILE_APPEND);
  1801. \file_put_contents(static::$_statisticsFile,
  1802. "pid\tmemory " . \str_pad('listening', static::$_maxSocketNameLength) . " " . \str_pad('worker_name',
  1803. static::$_maxWorkerNameLength) . " connections " . \str_pad('send_fail', 9) . " "
  1804. . \str_pad('timers', 8) . \str_pad('total_request', 13) ." qps status\n", \FILE_APPEND);
  1805. \chmod(static::$_statisticsFile, 0722);
  1806. foreach (static::getAllWorkerPids() as $worker_pid) {
  1807. \posix_kill($worker_pid, \SIGUSR2);
  1808. }
  1809. return;
  1810. }
  1811. // For child processes.
  1812. \reset(static::$_workers);
  1813. /** @var \Workerman\Worker $worker */
  1814. $worker = current(static::$_workers);
  1815. $worker_status_str = \posix_getpid() . "\t" . \str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M", 7)
  1816. . " " . \str_pad($worker->getSocketName(), static::$_maxSocketNameLength) . " "
  1817. . \str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::$_maxWorkerNameLength)
  1818. . " ";
  1819. $worker_status_str .= \str_pad(ConnectionInterface::$statistics['connection_count'], 11)
  1820. . " " . \str_pad(ConnectionInterface::$statistics['send_fail'], 9)
  1821. . " " . \str_pad(static::$globalEvent->getTimerCount(), 7)
  1822. . " " . \str_pad(ConnectionInterface::$statistics['total_request'], 13) . "\n";
  1823. \file_put_contents(static::$_statisticsFile, $worker_status_str, \FILE_APPEND);
  1824. }
  1825. /**
  1826. * Write statistics data to disk.
  1827. *
  1828. * @return void
  1829. */
  1830. protected static function writeConnectionsStatisticsToStatusFile()
  1831. {
  1832. // For master process.
  1833. if (static::$_masterPid === \posix_getpid()) {
  1834. \file_put_contents(static::$_statisticsFile, "--------------------------------------------------------------------- WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", \FILE_APPEND);
  1835. \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);
  1836. \chmod(static::$_statisticsFile, 0722);
  1837. foreach (static::getAllWorkerPids() as $worker_pid) {
  1838. \posix_kill($worker_pid, \SIGIO);
  1839. }
  1840. return;
  1841. }
  1842. // For child processes.
  1843. $bytes_format = function($bytes)
  1844. {
  1845. if($bytes > 1024*1024*1024*1024) {
  1846. return round($bytes/(1024*1024*1024*1024), 1)."TB";
  1847. }
  1848. if($bytes > 1024*1024*1024) {
  1849. return round($bytes/(1024*1024*1024), 1)."GB";
  1850. }
  1851. if($bytes > 1024*1024) {
  1852. return round($bytes/(1024*1024), 1)."MB";
  1853. }
  1854. if($bytes > 1024) {
  1855. return round($bytes/(1024), 1)."KB";
  1856. }
  1857. return $bytes."B";
  1858. };
  1859. $pid = \posix_getpid();
  1860. $str = '';
  1861. \reset(static::$_workers);
  1862. $current_worker = current(static::$_workers);
  1863. $default_worker_name = $current_worker->name;
  1864. /** @var \Workerman\Worker $worker */
  1865. foreach(TcpConnection::$connections as $connection) {
  1866. /** @var \Workerman\Connection\TcpConnection $connection */
  1867. $transport = $connection->transport;
  1868. $ipv4 = $connection->isIpV4() ? ' 1' : ' 0';
  1869. $ipv6 = $connection->isIpV6() ? ' 1' : ' 0';
  1870. $recv_q = $bytes_format($connection->getRecvBufferQueueSize());
  1871. $send_q = $bytes_format($connection->getSendBufferQueueSize());
  1872. $local_address = \trim($connection->getLocalAddress());
  1873. $remote_address = \trim($connection->getRemoteAddress());
  1874. $state = $connection->getStatus(false);
  1875. $bytes_read = $bytes_format($connection->bytesRead);
  1876. $bytes_written = $bytes_format($connection->bytesWritten);
  1877. $id = $connection->id;
  1878. $protocol = $connection->protocol ? $connection->protocol : $connection->transport;
  1879. $pos = \strrpos($protocol, '\\');
  1880. if ($pos) {
  1881. $protocol = \substr($protocol, $pos+1);
  1882. }
  1883. if (\strlen($protocol) > 15) {
  1884. $protocol = \substr($protocol, 0, 13) . '..';
  1885. }
  1886. $worker_name = isset($connection->worker) ? $connection->worker->name : $default_worker_name;
  1887. if (\strlen($worker_name) > 14) {
  1888. $worker_name = \substr($worker_name, 0, 12) . '..';
  1889. }
  1890. $str .= \str_pad($pid, 9) . \str_pad($worker_name, 16) . \str_pad($id, 10) . \str_pad($transport, 8)
  1891. . \str_pad($protocol, 16) . \str_pad($ipv4, 7) . \str_pad($ipv6, 7) . \str_pad($recv_q, 13)
  1892. . \str_pad($send_q, 13) . \str_pad($bytes_read, 13) . \str_pad($bytes_written, 13) . ' '
  1893. . \str_pad($state, 14) . ' ' . \str_pad($local_address, 22) . ' ' . \str_pad($remote_address, 22) ."\n";
  1894. }
  1895. if ($str) {
  1896. \file_put_contents(static::$_statisticsFile, $str, \FILE_APPEND);
  1897. }
  1898. }
  1899. /**
  1900. * Check errors when current process exited.
  1901. *
  1902. * @return void
  1903. */
  1904. public static function checkErrors()
  1905. {
  1906. if (static::STATUS_SHUTDOWN !== static::$_status) {
  1907. $error_msg = static::$_OS === \OS_TYPE_LINUX ? 'Worker['. \posix_getpid() .'] process terminated' : 'Worker process terminated';
  1908. $errors = error_get_last();
  1909. if ($errors && ($errors['type'] === \E_ERROR ||
  1910. $errors['type'] === \E_PARSE ||
  1911. $errors['type'] === \E_CORE_ERROR ||
  1912. $errors['type'] === \E_COMPILE_ERROR ||
  1913. $errors['type'] === \E_RECOVERABLE_ERROR)
  1914. ) {
  1915. $error_msg .= ' with ERROR: ' . static::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\"";
  1916. }
  1917. static::log($error_msg);
  1918. }
  1919. }
  1920. /**
  1921. * Get error message by error code.
  1922. *
  1923. * @param integer $type
  1924. * @return string
  1925. */
  1926. protected static function getErrorType($type)
  1927. {
  1928. if(isset(self::$_errorType[$type])) {
  1929. return self::$_errorType[$type];
  1930. }
  1931. return '';
  1932. }
  1933. /**
  1934. * Log.
  1935. *
  1936. * @param string $msg
  1937. * @return void
  1938. */
  1939. public static function log($msg)
  1940. {
  1941. $msg = $msg . "\n";
  1942. if (!static::$daemonize) {
  1943. static::safeEcho($msg);
  1944. }
  1945. \file_put_contents((string)static::$logFile, \date('Y-m-d H:i:s') . ' ' . 'pid:'
  1946. . (static::$_OS === \OS_TYPE_LINUX ? \posix_getpid() : 1) . ' ' . $msg, \FILE_APPEND | \LOCK_EX);
  1947. }
  1948. /**
  1949. * Safe Echo.
  1950. * @param string $msg
  1951. * @param bool $decorated
  1952. * @return bool
  1953. */
  1954. public static function safeEcho($msg, $decorated = false)
  1955. {
  1956. $stream = static::outputStream();
  1957. if (!$stream) {
  1958. return false;
  1959. }
  1960. if (!$decorated) {
  1961. $line = $white = $green = $end = '';
  1962. if (static::$_outputDecorated) {
  1963. $line = "\033[1A\n\033[K";
  1964. $white = "\033[47;30m";
  1965. $green = "\033[32;40m";
  1966. $end = "\033[0m";
  1967. }
  1968. $msg = \str_replace(array('<n>', '<w>', '<g>'), array($line, $white, $green), $msg);
  1969. $msg = \str_replace(array('</n>', '</w>', '</g>'), $end, $msg);
  1970. } elseif (!static::$_outputDecorated) {
  1971. return false;
  1972. }
  1973. \fwrite($stream, $msg);
  1974. \fflush($stream);
  1975. return true;
  1976. }
  1977. /**
  1978. * @param null $stream
  1979. * @return bool|resource
  1980. */
  1981. private static function outputStream($stream = null)
  1982. {
  1983. if (!$stream) {
  1984. $stream = static::$_outputStream ? static::$_outputStream : \STDOUT;
  1985. }
  1986. if (!$stream || !\is_resource($stream) || 'stream' !== \get_resource_type($stream)) {
  1987. return false;
  1988. }
  1989. $stat = \fstat($stream);
  1990. if (!$stat) {
  1991. return false;
  1992. }
  1993. if (($stat['mode'] & 0170000) === 0100000) {
  1994. // file
  1995. static::$_outputDecorated = false;
  1996. } else {
  1997. static::$_outputDecorated =
  1998. static::$_OS === \OS_TYPE_LINUX &&
  1999. \function_exists('posix_isatty') &&
  2000. \posix_isatty($stream);
  2001. }
  2002. return static::$_outputStream = $stream;
  2003. }
  2004. /**
  2005. * Construct.
  2006. *
  2007. * @param string $socket_name
  2008. * @param array $context_option
  2009. */
  2010. public function __construct($socket_name = '', array $context_option = array())
  2011. {
  2012. // Save all worker instances.
  2013. $this->workerId = \spl_object_hash($this);
  2014. static::$_workers[$this->workerId] = $this;
  2015. static::$_pidMap[$this->workerId] = array();
  2016. // Get autoload root path.
  2017. $backtrace = \debug_backtrace();
  2018. $this->_autoloadRootPath = \dirname($backtrace[0]['file']);
  2019. Autoloader::setRootPath($this->_autoloadRootPath);
  2020. // Context for socket.
  2021. if ($socket_name) {
  2022. $this->_socketName = $socket_name;
  2023. if (!isset($context_option['socket']['backlog'])) {
  2024. $context_option['socket']['backlog'] = static::DEFAULT_BACKLOG;
  2025. }
  2026. $this->_context = \stream_context_create($context_option);
  2027. }
  2028. // Turn reusePort on.
  2029. if (static::$_OS === \OS_TYPE_LINUX // if linux
  2030. && \version_compare(\PHP_VERSION,'7.0.0', 'ge') // if php >= 7.0.0
  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(\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. }