Worker.php 74 KB

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