Worker.php 79 KB

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