Worker.php 77 KB

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