Worker.php 79 KB

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