Worker.php 79 KB

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