Worker.php 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347
  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.10';
  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 Worker[]
  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. * Standard output stream
  394. * @var resource
  395. */
  396. protected static $_outputStream = null;
  397. /**
  398. * If $outputStream support decorated
  399. * @var bool
  400. */
  401. protected static $_outputDecorated = null;
  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. set_error_handler(function($code, $msg, $file, $line){
  444. Worker::safeEcho("$msg in file $file on line $line\n");
  445. });
  446. // Start file.
  447. $backtrace = debug_backtrace();
  448. static::$_startFile = $backtrace[count($backtrace) - 1]['file'];
  449. $unique_prefix = str_replace('/', '_', static::$_startFile);
  450. // Pid file.
  451. if (empty(static::$pidFile)) {
  452. static::$pidFile = __DIR__ . "/../$unique_prefix.pid";
  453. }
  454. // Log file.
  455. if (empty(static::$logFile)) {
  456. static::$logFile = __DIR__ . '/../workerman.log';
  457. }
  458. $log_file = (string)static::$logFile;
  459. if (!is_file($log_file)) {
  460. touch($log_file);
  461. chmod($log_file, 0622);
  462. }
  463. // State.
  464. static::$_status = static::STATUS_STARTING;
  465. // For statistics.
  466. static::$_globalStatistics['start_timestamp'] = time();
  467. static::$_statisticsFile = sys_get_temp_dir() . "/$unique_prefix.status";
  468. // Process title.
  469. static::setProcessTitle('WorkerMan: master process start_file=' . static::$_startFile);
  470. // Init data for worker id.
  471. static::initId();
  472. // Timer init.
  473. Timer::init();
  474. }
  475. /**
  476. * Init All worker instances.
  477. *
  478. * @return void
  479. */
  480. protected static function initWorkers()
  481. {
  482. if (static::$_OS !== OS_TYPE_LINUX) {
  483. return;
  484. }
  485. foreach (static::$_workers as $worker) {
  486. // Worker name.
  487. if (empty($worker->name)) {
  488. $worker->name = 'none';
  489. }
  490. // Get maximum length of worker name.
  491. $worker_name_length = strlen($worker->name);
  492. if (static::$_maxWorkerNameLength < $worker_name_length) {
  493. static::$_maxWorkerNameLength = $worker_name_length;
  494. }
  495. // Get maximum length of socket name.
  496. $socket_name_length = strlen($worker->getSocketName());
  497. if (static::$_maxSocketNameLength < $socket_name_length) {
  498. static::$_maxSocketNameLength = $socket_name_length;
  499. }
  500. // Get unix user of the worker process.
  501. if (empty($worker->user)) {
  502. $worker->user = static::getCurrentUser();
  503. } else {
  504. if (posix_getuid() !== 0 && $worker->user != static::getCurrentUser()) {
  505. static::log('Warning: You must have the root privileges to change uid and gid.');
  506. }
  507. }
  508. // Get maximum length of unix user name.
  509. $user_name_length = strlen($worker->user);
  510. if (static::$_maxUserNameLength < $user_name_length) {
  511. static::$_maxUserNameLength = $user_name_length;
  512. }
  513. // Listen.
  514. if (!$worker->reusePort) {
  515. $worker->listen();
  516. }
  517. }
  518. }
  519. /**
  520. * Get all worker instances.
  521. *
  522. * @return array
  523. */
  524. public static function getAllWorkers()
  525. {
  526. return static::$_workers;
  527. }
  528. /**
  529. * Get global event-loop instance.
  530. *
  531. * @return EventInterface
  532. */
  533. public static function getEventLoop()
  534. {
  535. return static::$globalEvent;
  536. }
  537. /**
  538. * Init idMap.
  539. * return void
  540. */
  541. protected static function initId()
  542. {
  543. foreach (static::$_workers as $worker_id => $worker) {
  544. $new_id_map = array();
  545. $worker->count = $worker->count <= 0 ? 1 : $worker->count;
  546. for($key = 0; $key < $worker->count; $key++) {
  547. $new_id_map[$key] = isset(static::$_idMap[$worker_id][$key]) ? static::$_idMap[$worker_id][$key] : 0;
  548. }
  549. static::$_idMap[$worker_id] = $new_id_map;
  550. }
  551. }
  552. /**
  553. * Get unix user of current porcess.
  554. *
  555. * @return string
  556. */
  557. protected static function getCurrentUser()
  558. {
  559. $user_info = posix_getpwuid(posix_getuid());
  560. return $user_info['name'];
  561. }
  562. /**
  563. * Display staring UI.
  564. *
  565. * @return void
  566. */
  567. protected static function displayUI()
  568. {
  569. global $argv;
  570. if (in_array('-q', $argv)) {
  571. return;
  572. }
  573. if (static::$_OS !== OS_TYPE_LINUX) {
  574. static::safeEcho("----------------------- WORKERMAN -----------------------------\r\n");
  575. static::safeEcho('Workerman version:'. static::VERSION. " PHP version:". PHP_VERSION. "\r\n");
  576. static::safeEcho("------------------------ WORKERS -------------------------------\r\n");
  577. static::safeEcho("worker listen processes status\r\n");
  578. return;
  579. }
  580. static::safeEcho("<n>-----------------------<w> WORKERMAN </w>-----------------------------</n>\r\n");
  581. static::safeEcho('Workerman version:'. static::VERSION. " PHP version:". PHP_VERSION. "\r\n");
  582. static::safeEcho("------------------------<w> WORKERS </w>-------------------------------\r\n");
  583. static::safeEcho("<w>user</w>". str_pad('',
  584. static::$_maxUserNameLength + 2 - strlen('user')). "<w>worker</w>". str_pad('',
  585. static::$_maxWorkerNameLength + 2 - strlen('worker')). "<w>listen</w>". str_pad('',
  586. static::$_maxSocketNameLength + 2 - strlen('listen')). "<w>processes</w> <w>status</w>\n");
  587. foreach (static::$_workers as $worker) {
  588. static::safeEcho(str_pad($worker->user, static::$_maxUserNameLength + 2). str_pad($worker->name,
  589. static::$_maxWorkerNameLength + 2). str_pad($worker->getSocketName(),
  590. static::$_maxSocketNameLength + 2). str_pad(' ' . $worker->count, 9). " <g> [OK] </g>\n");
  591. }
  592. static::safeEcho("----------------------------------------------------------------\n");
  593. if (static::$daemonize) {
  594. static::safeEcho("Input \"php $argv[0] stop\" to stop. Start success.\n\n");
  595. } else {
  596. static::safeEcho("Press Ctrl+C to stop. Start success.\n");
  597. }
  598. }
  599. /**
  600. * Parse command.
  601. *
  602. * @return void
  603. */
  604. protected static function parseCommand()
  605. {
  606. if (static::$_OS !== OS_TYPE_LINUX) {
  607. return;
  608. }
  609. global $argv;
  610. // Check argv;
  611. $start_file = $argv[0];
  612. $available_commands = array(
  613. 'start',
  614. 'stop',
  615. 'restart',
  616. 'reload',
  617. 'status',
  618. 'connections',
  619. );
  620. $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";
  621. if (!isset($argv[1]) || !in_array($argv[1], $available_commands)) {
  622. if (isset($argv[1])) {
  623. static::safeEcho('Unknown command: ' . $argv[1] . "\n");
  624. }
  625. exit($usage);
  626. }
  627. // Get command.
  628. $command = trim($argv[1]);
  629. $command2 = isset($argv[2]) ? $argv[2] : '';
  630. // Start command.
  631. $mode = '';
  632. if ($command === 'start') {
  633. if ($command2 === '-d' || static::$daemonize) {
  634. $mode = 'in DAEMON mode';
  635. } else {
  636. $mode = 'in DEBUG mode';
  637. }
  638. }
  639. static::log("Workerman[$start_file] $command $mode");
  640. // Get master process PID.
  641. $master_pid = is_file(static::$pidFile) ? file_get_contents(static::$pidFile) : 0;
  642. $master_is_alive = $master_pid && posix_kill($master_pid, 0) && posix_getpid() != $master_pid;
  643. // Master is still alive?
  644. if ($master_is_alive) {
  645. if ($command === 'start') {
  646. static::log("Workerman[$start_file] already running");
  647. exit;
  648. }
  649. } elseif ($command !== 'start' && $command !== 'restart') {
  650. static::log("Workerman[$start_file] not run");
  651. exit;
  652. }
  653. // execute command.
  654. switch ($command) {
  655. case 'start':
  656. if ($command2 === '-d') {
  657. static::$daemonize = true;
  658. }
  659. break;
  660. case 'status':
  661. while (1) {
  662. if (is_file(static::$_statisticsFile)) {
  663. @unlink(static::$_statisticsFile);
  664. }
  665. // Master process will send SIGUSR2 signal to all child processes.
  666. posix_kill($master_pid, SIGUSR2);
  667. // Sleep 1 second.
  668. sleep(1);
  669. // Clear terminal.
  670. if ($command2 === '-d') {
  671. static::safeEcho("\33[H\33[2J\33(B\33[m", true);
  672. }
  673. // Echo status data.
  674. static::safeEcho(static::formatStatusData());
  675. if ($command2 !== '-d') {
  676. exit(0);
  677. }
  678. static::safeEcho("\nPress Ctrl+C to quit.\n\n");
  679. }
  680. exit(0);
  681. case 'connections':
  682. if (is_file(static::$_statisticsFile) && is_writable(static::$_statisticsFile)) {
  683. unlink(static::$_statisticsFile);
  684. }
  685. // Master process will send SIGIO signal to all child processes.
  686. posix_kill($master_pid, SIGIO);
  687. // Waiting amoment.
  688. usleep(500000);
  689. // Display statisitcs data from a disk file.
  690. if(is_readable(static::$_statisticsFile)) {
  691. readfile(static::$_statisticsFile);
  692. }
  693. exit(0);
  694. case 'restart':
  695. case 'stop':
  696. if ($command2 === '-g') {
  697. static::$_gracefulStop = true;
  698. $sig = SIGTERM;
  699. static::log("Workerman[$start_file] is gracefully stopping ...");
  700. } else {
  701. static::$_gracefulStop = false;
  702. $sig = SIGINT;
  703. static::log("Workerman[$start_file] is stopping ...");
  704. }
  705. // Send stop signal to master process.
  706. $master_pid && posix_kill($master_pid, $sig);
  707. // Timeout.
  708. $timeout = 5;
  709. $start_time = time();
  710. // Check master process is still alive?
  711. while (1) {
  712. $master_is_alive = $master_pid && posix_kill($master_pid, 0);
  713. if ($master_is_alive) {
  714. // Timeout?
  715. if (!static::$_gracefulStop && time() - $start_time >= $timeout) {
  716. static::log("Workerman[$start_file] stop fail");
  717. exit;
  718. }
  719. // Waiting amoment.
  720. usleep(10000);
  721. continue;
  722. }
  723. // Stop success.
  724. static::log("Workerman[$start_file] stop success");
  725. if ($command === 'stop') {
  726. exit(0);
  727. }
  728. if ($command2 === '-d') {
  729. static::$daemonize = true;
  730. }
  731. break;
  732. }
  733. break;
  734. case 'reload':
  735. if($command2 === '-g'){
  736. $sig = SIGQUIT;
  737. }else{
  738. $sig = SIGUSR1;
  739. }
  740. posix_kill($master_pid, $sig);
  741. exit;
  742. default :
  743. if (isset($command)) {
  744. static::safeEcho('Unknown command: ' . $command . "\n");
  745. }
  746. exit($usage);
  747. }
  748. }
  749. /**
  750. * Format status data.
  751. *
  752. * @return string
  753. */
  754. protected static function formatStatusData()
  755. {
  756. static $total_request_cache = array();
  757. if (!is_readable(static::$_statisticsFile)) {
  758. return '';
  759. }
  760. $info = file(static::$_statisticsFile, FILE_IGNORE_NEW_LINES);
  761. if (!$info) {
  762. return '';
  763. }
  764. $status_str = '';
  765. $current_total_request = array();
  766. $worker_info = json_decode($info[0], true);
  767. ksort($worker_info, SORT_NUMERIC);
  768. unset($info[0]);
  769. $data_waiting_sort = array();
  770. $read_process_status = false;
  771. $total_requests = 0;
  772. $total_qps = 0;
  773. $total_connections = 0;
  774. $total_fails = 0;
  775. $total_memory = 0;
  776. $total_timers = 0;
  777. $maxLen1 = static::$_maxSocketNameLength;
  778. $maxLen2 = static::$_maxWorkerNameLength;
  779. foreach($info as $key => $value) {
  780. if (!$read_process_status) {
  781. $status_str .= $value . "\n";
  782. if (preg_match('/^pid.*?memory.*?listening/', $value)) {
  783. $read_process_status = true;
  784. }
  785. continue;
  786. }
  787. if(preg_match('/^[0-9]+/', $value, $pid_math)) {
  788. $pid = $pid_math[0];
  789. $data_waiting_sort[$pid] = $value;
  790. if(preg_match('/^\S+?\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?/', $value, $match)) {
  791. $total_memory += intval(str_ireplace('M','',$match[1]));
  792. $maxLen1 = max($maxLen1,strlen($match[2]));
  793. $maxLen2 = max($maxLen2,strlen($match[3]));
  794. $total_connections += intval($match[4]);
  795. $total_fails += intval($match[5]);
  796. $total_timers += intval($match[6]);
  797. $current_total_request[$pid] = $match[7];
  798. $total_requests += intval($match[7]);
  799. }
  800. }
  801. }
  802. foreach($worker_info as $pid => $info) {
  803. if (!isset($data_waiting_sort[$pid])) {
  804. $status_str .= "$pid\t" . str_pad('N/A', 7) . " "
  805. . str_pad($info['listen'], static::$_maxSocketNameLength) . " "
  806. . str_pad($info['name'], static::$_maxWorkerNameLength) . " "
  807. . str_pad('N/A', 11) . " " . str_pad('N/A', 9) . " "
  808. . str_pad('N/A', 7) . " " . str_pad('N/A', 13) . " N/A [busy] \n";
  809. continue;
  810. }
  811. //$qps = isset($total_request_cache[$pid]) ? $current_total_request[$pid]
  812. if (!isset($total_request_cache[$pid]) || !isset($current_total_request[$pid])) {
  813. $qps = 0;
  814. } else {
  815. $qps = $current_total_request[$pid] - $total_request_cache[$pid];
  816. $total_qps += $qps;
  817. }
  818. $status_str .= $data_waiting_sort[$pid]. " " . str_pad($qps, 6) ." [idle]\n";
  819. }
  820. $total_request_cache = $current_total_request;
  821. $status_str .= "----------------------------------------------PROCESS STATUS---------------------------------------------------\n";
  822. $status_str .= "Summary\t" . str_pad($total_memory.'M', 7) . " "
  823. . str_pad('-', $maxLen1) . " "
  824. . str_pad('-', $maxLen2) . " "
  825. . str_pad($total_connections, 11) . " " . str_pad($total_fails, 9) . " "
  826. . str_pad($total_timers, 7) . " " . str_pad($total_requests, 13) . " "
  827. . str_pad($total_qps,6)." [Summary] \n";
  828. return $status_str;
  829. }
  830. /**
  831. * Install signal handler.
  832. *
  833. * @return void
  834. */
  835. protected static function installSignal()
  836. {
  837. if (static::$_OS !== OS_TYPE_LINUX) {
  838. return;
  839. }
  840. // stop
  841. pcntl_signal(SIGINT, array('\Workerman\Worker', 'signalHandler'), false);
  842. // graceful stop
  843. pcntl_signal(SIGTERM, array('\Workerman\Worker', 'signalHandler'), false);
  844. // reload
  845. pcntl_signal(SIGUSR1, array('\Workerman\Worker', 'signalHandler'), false);
  846. // graceful reload
  847. pcntl_signal(SIGQUIT, array('\Workerman\Worker', 'signalHandler'), false);
  848. // status
  849. pcntl_signal(SIGUSR2, array('\Workerman\Worker', 'signalHandler'), false);
  850. // connection status
  851. pcntl_signal(SIGIO, array('\Workerman\Worker', 'signalHandler'), false);
  852. // ignore
  853. pcntl_signal(SIGPIPE, SIG_IGN, false);
  854. }
  855. /**
  856. * Reinstall signal handler.
  857. *
  858. * @return void
  859. */
  860. protected static function reinstallSignal()
  861. {
  862. if (static::$_OS !== OS_TYPE_LINUX) {
  863. return;
  864. }
  865. // uninstall stop signal handler
  866. pcntl_signal(SIGINT, SIG_IGN, false);
  867. // uninstall graceful stop signal handler
  868. pcntl_signal(SIGTERM, SIG_IGN, false);
  869. // uninstall reload signal handler
  870. pcntl_signal(SIGUSR1, SIG_IGN, false);
  871. // uninstall graceful reload signal handler
  872. pcntl_signal(SIGQUIT, SIG_IGN, false);
  873. // uninstall status signal handler
  874. pcntl_signal(SIGUSR2, SIG_IGN, false);
  875. // reinstall stop signal handler
  876. static::$globalEvent->add(SIGINT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  877. // reinstall graceful stop signal handler
  878. static::$globalEvent->add(SIGTERM, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  879. // reinstall reload signal handler
  880. static::$globalEvent->add(SIGUSR1, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  881. // reinstall graceful reload signal handler
  882. static::$globalEvent->add(SIGQUIT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  883. // reinstall status signal handler
  884. static::$globalEvent->add(SIGUSR2, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  885. // reinstall connection status signal handler
  886. static::$globalEvent->add(SIGIO, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  887. }
  888. /**
  889. * Signal handler.
  890. *
  891. * @param int $signal
  892. */
  893. public static function signalHandler($signal)
  894. {
  895. switch ($signal) {
  896. // Stop.
  897. case SIGINT:
  898. static::$_gracefulStop = false;
  899. static::stopAll();
  900. break;
  901. // Graceful stop.
  902. case SIGTERM:
  903. static::$_gracefulStop = true;
  904. static::stopAll();
  905. break;
  906. // Reload.
  907. case SIGQUIT:
  908. case SIGUSR1:
  909. if($signal === SIGQUIT){
  910. static::$_gracefulStop = true;
  911. }else{
  912. static::$_gracefulStop = false;
  913. }
  914. static::$_pidsToRestart = static::getAllWorkerPids();
  915. static::reload();
  916. break;
  917. // Show status.
  918. case SIGUSR2:
  919. static::writeStatisticsToStatusFile();
  920. break;
  921. // Show connection status.
  922. case SIGIO:
  923. static::writeConnectionsStatisticsToStatusFile();
  924. break;
  925. }
  926. }
  927. /**
  928. * Run as deamon mode.
  929. *
  930. * @throws Exception
  931. */
  932. protected static function daemonize()
  933. {
  934. if (!static::$daemonize || static::$_OS !== OS_TYPE_LINUX) {
  935. return;
  936. }
  937. umask(0);
  938. $pid = pcntl_fork();
  939. if (-1 === $pid) {
  940. throw new Exception('fork fail');
  941. } elseif ($pid > 0) {
  942. exit(0);
  943. }
  944. if (-1 === posix_setsid()) {
  945. throw new Exception("setsid fail");
  946. }
  947. // Fork again avoid SVR4 system regain the control of terminal.
  948. $pid = pcntl_fork();
  949. if (-1 === $pid) {
  950. throw new Exception("fork fail");
  951. } elseif (0 !== $pid) {
  952. exit(0);
  953. }
  954. }
  955. /**
  956. * Redirect standard input and output.
  957. *
  958. * @throws Exception
  959. */
  960. public static function resetStd()
  961. {
  962. if (!static::$daemonize || static::$_OS !== OS_TYPE_LINUX) {
  963. return;
  964. }
  965. global $STDOUT, $STDERR;
  966. $handle = fopen(static::$stdoutFile, "a");
  967. if ($handle) {
  968. unset($handle);
  969. set_error_handler(function(){});
  970. fclose($STDOUT);
  971. fclose($STDERR);
  972. fclose(STDOUT);
  973. fclose(STDERR);
  974. $STDOUT = fopen(static::$stdoutFile, "a");
  975. $STDERR = fopen(static::$stdoutFile, "a");
  976. // change output stream
  977. static::$_outputStream = null;
  978. static::outputStream($STDOUT);
  979. restore_error_handler();
  980. } else {
  981. throw new Exception('can not open stdoutFile ' . static::$stdoutFile);
  982. }
  983. }
  984. /**
  985. * Save pid.
  986. *
  987. * @throws Exception
  988. */
  989. protected static function saveMasterPid()
  990. {
  991. if (static::$_OS !== OS_TYPE_LINUX) {
  992. return;
  993. }
  994. static::$_masterPid = posix_getpid();
  995. if (false === file_put_contents(static::$pidFile, static::$_masterPid)) {
  996. throw new Exception('can not save pid to ' . static::$pidFile);
  997. }
  998. }
  999. /**
  1000. * Get event loop name.
  1001. *
  1002. * @return string
  1003. */
  1004. protected static function getEventLoopName()
  1005. {
  1006. if (static::$eventLoopClass) {
  1007. return static::$eventLoopClass;
  1008. }
  1009. $loop_name = '';
  1010. foreach (static::$_availableEventLoops as $name=>$class) {
  1011. if (extension_loaded($name)) {
  1012. $loop_name = $name;
  1013. break;
  1014. }
  1015. }
  1016. if ($loop_name) {
  1017. if (interface_exists('\React\EventLoop\LoopInterface')) {
  1018. switch ($loop_name) {
  1019. case 'libevent':
  1020. static::$eventLoopClass = '\Workerman\Events\React\ExtLibEventLoop';
  1021. break;
  1022. case 'event':
  1023. static::$eventLoopClass = '\Workerman\Events\React\ExtEventLoop';
  1024. break;
  1025. default :
  1026. static::$eventLoopClass = '\Workerman\Events\React\StreamSelectLoop';
  1027. break;
  1028. }
  1029. } else {
  1030. static::$eventLoopClass = static::$_availableEventLoops[$loop_name];
  1031. }
  1032. } else {
  1033. static::$eventLoopClass = interface_exists('\React\EventLoop\LoopInterface')? '\Workerman\Events\React\StreamSelectLoop':'\Workerman\Events\Select';
  1034. }
  1035. return static::$eventLoopClass;
  1036. }
  1037. /**
  1038. * Get all pids of worker processes.
  1039. *
  1040. * @return array
  1041. */
  1042. protected static function getAllWorkerPids()
  1043. {
  1044. $pid_array = array();
  1045. foreach (static::$_pidMap as $worker_pid_array) {
  1046. foreach ($worker_pid_array as $worker_pid) {
  1047. $pid_array[$worker_pid] = $worker_pid;
  1048. }
  1049. }
  1050. return $pid_array;
  1051. }
  1052. /**
  1053. * Fork some worker processes.
  1054. *
  1055. * @return void
  1056. */
  1057. protected static function forkWorkers()
  1058. {
  1059. if (static::$_OS === OS_TYPE_LINUX) {
  1060. static::forkWorkersForLinux();
  1061. } else {
  1062. static::forkWorkersForWindows();
  1063. }
  1064. }
  1065. /**
  1066. * Fork some worker processes.
  1067. *
  1068. * @return void
  1069. */
  1070. protected static function forkWorkersForLinux()
  1071. {
  1072. foreach (static::$_workers as $worker) {
  1073. if (static::$_status === static::STATUS_STARTING) {
  1074. if (empty($worker->name)) {
  1075. $worker->name = $worker->getSocketName();
  1076. }
  1077. $worker_name_length = strlen($worker->name);
  1078. if (static::$_maxWorkerNameLength < $worker_name_length) {
  1079. static::$_maxWorkerNameLength = $worker_name_length;
  1080. }
  1081. }
  1082. while (count(static::$_pidMap[$worker->workerId]) < $worker->count) {
  1083. static::forkOneWorkerForLinux($worker);
  1084. }
  1085. }
  1086. }
  1087. /**
  1088. * Fork some worker processes.
  1089. *
  1090. * @return void
  1091. */
  1092. protected static function forkWorkersForWindows()
  1093. {
  1094. $files = static::getStartFilesForWindows();
  1095. global $argv;
  1096. if(in_array('-q', $argv) || count($files) === 1)
  1097. {
  1098. if(count(static::$_workers) > 1)
  1099. {
  1100. static::safeEcho("@@@ Error: multi workers init in one php file are not support @@@\r\n");
  1101. static::safeEcho("@@@ Please visit http://wiki.workerman.net/Multi_woker_for_win @@@\r\n");
  1102. }
  1103. elseif(count(static::$_workers) <= 0)
  1104. {
  1105. exit("@@@no worker inited@@@\r\n\r\n");
  1106. }
  1107. reset(static::$_workers);
  1108. /** @var Worker $worker */
  1109. $worker = current(static::$_workers);
  1110. // Display UI.
  1111. static::safeEcho(str_pad($worker->name, 21) . str_pad($worker->getSocketName(), 36) . str_pad($worker->count, 10) . "[ok]\n");
  1112. $worker->listen();
  1113. $worker->run();
  1114. exit("@@@child exit@@@\r\n");
  1115. }
  1116. else
  1117. {
  1118. static::$globalEvent = new \Workerman\Events\Select();
  1119. Timer::init(static::$globalEvent);
  1120. foreach($files as $start_file)
  1121. {
  1122. static::forkOneWorkerForWindows($start_file);
  1123. }
  1124. }
  1125. }
  1126. /**
  1127. * Get start files for windows.
  1128. *
  1129. * @return array
  1130. */
  1131. public static function getStartFilesForWindows() {
  1132. global $argv;
  1133. $files = array();
  1134. foreach($argv as $file)
  1135. {
  1136. if(is_file($file))
  1137. {
  1138. $files[$file] = $file;
  1139. }
  1140. }
  1141. return $files;
  1142. }
  1143. /**
  1144. * Fork one worker process.
  1145. *
  1146. * @param string $start_file
  1147. */
  1148. public static function forkOneWorkerForWindows($start_file)
  1149. {
  1150. $start_file = realpath($start_file);
  1151. $std_file = sys_get_temp_dir() . '/'.str_replace(array('/', "\\", ':'), '_', $start_file).'.out.txt';
  1152. $descriptorspec = array(
  1153. 0 => array('pipe', 'a'), // stdin
  1154. 1 => array('file', $std_file, 'w'), // stdout
  1155. 2 => array('file', $std_file, 'w') // stderr
  1156. );
  1157. $pipes = array();
  1158. $process = proc_open("php \"$start_file\" -q", $descriptorspec, $pipes);
  1159. $std_handler = fopen($std_file, 'a+');
  1160. stream_set_blocking($std_handler, 0);
  1161. if (empty(static::$globalEvent)) {
  1162. static::$globalEvent = new Select();
  1163. Timer::init(static::$globalEvent);
  1164. }
  1165. $timer_id = Timer::add(1, function()use($std_handler)
  1166. {
  1167. Worker::safeEcho(fread($std_handler, 65535));
  1168. });
  1169. // 保存子进程句柄
  1170. static::$_processForWindows[$start_file] = array($process, $start_file, $timer_id);
  1171. }
  1172. /**
  1173. * check worker status for windows.
  1174. * @return void
  1175. */
  1176. public static function checkWorkerStatusForWindows()
  1177. {
  1178. foreach(static::$_processForWindows as $process_data)
  1179. {
  1180. $process = $process_data[0];
  1181. $start_file = $process_data[1];
  1182. $timer_id = $process_data[2];
  1183. $status = proc_get_status($process);
  1184. if(isset($status['running']))
  1185. {
  1186. if(!$status['running'])
  1187. {
  1188. static::safeEcho("process $start_file terminated and try to restart\n");
  1189. Timer::del($timer_id);
  1190. proc_close($process);
  1191. static::forkOneWorkerForWindows($start_file);
  1192. }
  1193. }
  1194. else
  1195. {
  1196. static::safeEcho("proc_get_status fail\n");
  1197. }
  1198. }
  1199. }
  1200. /**
  1201. * Fork one worker process.
  1202. *
  1203. * @param \Workerman\Worker $worker
  1204. * @throws Exception
  1205. */
  1206. protected static function forkOneWorkerForLinux($worker)
  1207. {
  1208. // Get available worker id.
  1209. $id = static::getId($worker->workerId, 0);
  1210. if ($id === false) {
  1211. return;
  1212. }
  1213. $pid = pcntl_fork();
  1214. // For master process.
  1215. if ($pid > 0) {
  1216. static::$_pidMap[$worker->workerId][$pid] = $pid;
  1217. static::$_idMap[$worker->workerId][$id] = $pid;
  1218. } // For child processes.
  1219. elseif (0 === $pid) {
  1220. if ($worker->reusePort) {
  1221. $worker->listen();
  1222. }
  1223. if (static::$_status === static::STATUS_STARTING) {
  1224. static::resetStd();
  1225. }
  1226. static::$_pidMap = array();
  1227. // Remove other listener.
  1228. foreach(static::$_workers as $key => $one_worker) {
  1229. if ($one_worker->workerId !== $worker->workerId) {
  1230. $one_worker->unlisten();
  1231. unset(static::$_workers[$key]);
  1232. }
  1233. }
  1234. Timer::delAll();
  1235. static::setProcessTitle('WorkerMan: worker process ' . $worker->name . ' ' . $worker->getSocketName());
  1236. $worker->setUserAndGroup();
  1237. $worker->id = $id;
  1238. $worker->run();
  1239. $err = new Exception('event-loop exited');
  1240. static::log($err);
  1241. exit(250);
  1242. } else {
  1243. throw new Exception("forkOneWorker fail");
  1244. }
  1245. }
  1246. /**
  1247. * Get worker id.
  1248. *
  1249. * @param int $worker_id
  1250. * @param int $pid
  1251. *
  1252. * @return integer
  1253. */
  1254. protected static function getId($worker_id, $pid)
  1255. {
  1256. return array_search($pid, static::$_idMap[$worker_id]);
  1257. }
  1258. /**
  1259. * Set unix user and group for current process.
  1260. *
  1261. * @return void
  1262. */
  1263. public function setUserAndGroup()
  1264. {
  1265. // Get uid.
  1266. $user_info = posix_getpwnam($this->user);
  1267. if (!$user_info) {
  1268. static::log("Warning: User {$this->user} not exsits");
  1269. return;
  1270. }
  1271. $uid = $user_info['uid'];
  1272. // Get gid.
  1273. if ($this->group) {
  1274. $group_info = posix_getgrnam($this->group);
  1275. if (!$group_info) {
  1276. static::log("Warning: Group {$this->group} not exsits");
  1277. return;
  1278. }
  1279. $gid = $group_info['gid'];
  1280. } else {
  1281. $gid = $user_info['gid'];
  1282. }
  1283. // Set uid and gid.
  1284. if ($uid != posix_getuid() || $gid != posix_getgid()) {
  1285. if (!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid)) {
  1286. static::log("Warning: change gid or uid fail.");
  1287. }
  1288. }
  1289. }
  1290. /**
  1291. * Set process name.
  1292. *
  1293. * @param string $title
  1294. * @return void
  1295. */
  1296. protected static function setProcessTitle($title)
  1297. {
  1298. set_error_handler(function(){});
  1299. // >=php 5.5
  1300. if (function_exists('cli_set_process_title')) {
  1301. cli_set_process_title($title);
  1302. } // Need proctitle when php<=5.5 .
  1303. elseif (extension_loaded('proctitle') && function_exists('setproctitle')) {
  1304. setproctitle($title);
  1305. }
  1306. restore_error_handler();
  1307. }
  1308. /**
  1309. * Monitor all child processes.
  1310. *
  1311. * @return void
  1312. */
  1313. protected static function monitorWorkers()
  1314. {
  1315. if (static::$_OS === OS_TYPE_LINUX) {
  1316. static::monitorWorkersForLinux();
  1317. } else {
  1318. static::monitorWorkersForWindows();
  1319. }
  1320. }
  1321. /**
  1322. * Monitor all child processes.
  1323. *
  1324. * @return void
  1325. */
  1326. protected static function monitorWorkersForLinux()
  1327. {
  1328. static::$_status = static::STATUS_RUNNING;
  1329. while (1) {
  1330. // Calls signal handlers for pending signals.
  1331. pcntl_signal_dispatch();
  1332. // Suspends execution of the current process until a child has exited, or until a signal is delivered
  1333. $status = 0;
  1334. $pid = pcntl_wait($status, WUNTRACED);
  1335. // Calls signal handlers for pending signals again.
  1336. pcntl_signal_dispatch();
  1337. // If a child has already exited.
  1338. if ($pid > 0) {
  1339. // Find out witch worker process exited.
  1340. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1341. if (isset($worker_pid_array[$pid])) {
  1342. $worker = static::$_workers[$worker_id];
  1343. // Exit status.
  1344. if ($status !== 0) {
  1345. static::log("worker[" . $worker->name . ":$pid] exit with status $status");
  1346. }
  1347. // For Statistics.
  1348. if (!isset(static::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
  1349. static::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;
  1350. }
  1351. static::$_globalStatistics['worker_exit_info'][$worker_id][$status]++;
  1352. // Clear process data.
  1353. unset(static::$_pidMap[$worker_id][$pid]);
  1354. // Mark id is available.
  1355. $id = static::getId($worker_id, $pid);
  1356. static::$_idMap[$worker_id][$id] = 0;
  1357. break;
  1358. }
  1359. }
  1360. // Is still running state then fork a new worker process.
  1361. if (static::$_status !== static::STATUS_SHUTDOWN) {
  1362. static::forkWorkers();
  1363. // If reloading continue.
  1364. if (isset(static::$_pidsToRestart[$pid])) {
  1365. unset(static::$_pidsToRestart[$pid]);
  1366. static::reload();
  1367. }
  1368. } else {
  1369. // If shutdown state and all child processes exited then master process exit.
  1370. if (!static::getAllWorkerPids()) {
  1371. static::exitAndClearAll();
  1372. }
  1373. }
  1374. } else {
  1375. // If shutdown state and all child processes exited then master process exit.
  1376. if (static::$_status === static::STATUS_SHUTDOWN && !static::getAllWorkerPids()) {
  1377. static::exitAndClearAll();
  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. Timer::add(1, "\\Workerman\\Worker::checkIfChildRunning");
  1523. // Remove statistics file.
  1524. if (is_file(static::$_statisticsFile)) {
  1525. @unlink(static::$_statisticsFile);
  1526. }
  1527. } // For child processes.
  1528. else {
  1529. // Execute exit.
  1530. foreach (static::$_workers as $worker) {
  1531. if(!$worker->stopping){
  1532. $worker->stop();
  1533. $worker->stopping = true;
  1534. }
  1535. }
  1536. if (!static::$_gracefulStop || ConnectionInterface::$statistics['connection_count'] <= 0) {
  1537. static::$_workers = array();
  1538. if (static::$globalEvent) {
  1539. static::$globalEvent->destroy();
  1540. }
  1541. exit(0);
  1542. }
  1543. }
  1544. }
  1545. /**
  1546. * check if child processes is really running
  1547. */
  1548. public static function checkIfChildRunning()
  1549. {
  1550. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1551. foreach ($worker_pid_array as $pid => $worker_pid) {
  1552. if (!posix_kill($pid, 0)) {
  1553. unset(static::$_pidMap[$worker_id][$pid]);
  1554. }
  1555. }
  1556. }
  1557. }
  1558. /**
  1559. * Get process status.
  1560. *
  1561. * @return number
  1562. */
  1563. public static function getStatus()
  1564. {
  1565. return static::$_status;
  1566. }
  1567. /**
  1568. * If stop gracefully.
  1569. *
  1570. * @return boolean
  1571. */
  1572. public static function getGracefulStop()
  1573. {
  1574. return static::$_gracefulStop;
  1575. }
  1576. /**
  1577. * Write statistics data to disk.
  1578. *
  1579. * @return void
  1580. */
  1581. protected static function writeStatisticsToStatusFile()
  1582. {
  1583. // For master process.
  1584. if (static::$_masterPid === posix_getpid()) {
  1585. $all_worker_info = array();
  1586. foreach(static::$_pidMap as $worker_id => $pid_array) {
  1587. /** @var /Workerman/Worker $worker */
  1588. $worker = static::$_workers[$worker_id];
  1589. foreach($pid_array as $pid) {
  1590. $all_worker_info[$pid] = array('name' => $worker->name, 'listen' => $worker->getSocketName());
  1591. }
  1592. }
  1593. file_put_contents(static::$_statisticsFile, json_encode($all_worker_info)."\n", FILE_APPEND);
  1594. $loadavg = function_exists('sys_getloadavg') ? array_map('round', sys_getloadavg(), array(2)) : array('-', '-', '-');
  1595. file_put_contents(static::$_statisticsFile,
  1596. "----------------------------------------------GLOBAL STATUS----------------------------------------------------\n", FILE_APPEND);
  1597. file_put_contents(static::$_statisticsFile,
  1598. 'Workerman version:' . static::VERSION . " PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
  1599. file_put_contents(static::$_statisticsFile, 'start time:' . date('Y-m-d H:i:s',
  1600. 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",
  1601. FILE_APPEND);
  1602. $load_str = 'load average: ' . implode(", ", $loadavg);
  1603. file_put_contents(static::$_statisticsFile,
  1604. str_pad($load_str, 33) . 'event-loop:' . static::getEventLoopName() . "\n", FILE_APPEND);
  1605. file_put_contents(static::$_statisticsFile,
  1606. count(static::$_pidMap) . ' workers ' . count(static::getAllWorkerPids()) . " processes\n",
  1607. FILE_APPEND);
  1608. file_put_contents(static::$_statisticsFile,
  1609. str_pad('worker_name', static::$_maxWorkerNameLength) . " exit_status exit_count\n", FILE_APPEND);
  1610. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1611. $worker = static::$_workers[$worker_id];
  1612. if (isset(static::$_globalStatistics['worker_exit_info'][$worker_id])) {
  1613. foreach (static::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
  1614. file_put_contents(static::$_statisticsFile,
  1615. str_pad($worker->name, static::$_maxWorkerNameLength) . " " . str_pad($worker_exit_status,
  1616. 16) . " $worker_exit_count\n", FILE_APPEND);
  1617. }
  1618. } else {
  1619. file_put_contents(static::$_statisticsFile,
  1620. str_pad($worker->name, static::$_maxWorkerNameLength) . " " . str_pad(0, 16) . " 0\n",
  1621. FILE_APPEND);
  1622. }
  1623. }
  1624. file_put_contents(static::$_statisticsFile,
  1625. "----------------------------------------------PROCESS STATUS---------------------------------------------------\n",
  1626. FILE_APPEND);
  1627. file_put_contents(static::$_statisticsFile,
  1628. "pid\tmemory " . str_pad('listening', static::$_maxSocketNameLength) . " " . str_pad('worker_name',
  1629. static::$_maxWorkerNameLength) . " connections " . str_pad('send_fail', 9) . " "
  1630. . str_pad('timers', 8) . str_pad('total_request', 13) ." qps status\n", FILE_APPEND);
  1631. chmod(static::$_statisticsFile, 0722);
  1632. foreach (static::getAllWorkerPids() as $worker_pid) {
  1633. posix_kill($worker_pid, SIGUSR2);
  1634. }
  1635. return;
  1636. }
  1637. // For child processes.
  1638. reset(static::$_workers);
  1639. /** @var \Workerman\Worker $worker */
  1640. $worker = current(static::$_workers);
  1641. $worker_status_str = posix_getpid() . "\t" . str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M", 7)
  1642. . " " . str_pad($worker->getSocketName(), static::$_maxSocketNameLength) . " "
  1643. . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::$_maxWorkerNameLength)
  1644. . " ";
  1645. $worker_status_str .= str_pad(ConnectionInterface::$statistics['connection_count'], 11)
  1646. . " " . str_pad(ConnectionInterface::$statistics['send_fail'], 9)
  1647. . " " . str_pad(static::$globalEvent->getTimerCount(), 7)
  1648. . " " . str_pad(ConnectionInterface::$statistics['total_request'], 13) . "\n";
  1649. file_put_contents(static::$_statisticsFile, $worker_status_str, FILE_APPEND);
  1650. }
  1651. /**
  1652. * Write statistics data to disk.
  1653. *
  1654. * @return void
  1655. */
  1656. protected static function writeConnectionsStatisticsToStatusFile()
  1657. {
  1658. // For master process.
  1659. if (static::$_masterPid === posix_getpid()) {
  1660. file_put_contents(static::$_statisticsFile, "--------------------------------------------------------------------- WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", FILE_APPEND);
  1661. 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);
  1662. chmod(static::$_statisticsFile, 0722);
  1663. foreach (static::getAllWorkerPids() as $worker_pid) {
  1664. posix_kill($worker_pid, SIGIO);
  1665. }
  1666. return;
  1667. }
  1668. // For child processes.
  1669. $bytes_format = function($bytes)
  1670. {
  1671. if($bytes > 1024*1024*1024*1024) {
  1672. return round($bytes/(1024*1024*1024*1024), 1)."TB";
  1673. }
  1674. if($bytes > 1024*1024*1024) {
  1675. return round($bytes/(1024*1024*1024), 1)."GB";
  1676. }
  1677. if($bytes > 1024*1024) {
  1678. return round($bytes/(1024*1024), 1)."MB";
  1679. }
  1680. if($bytes > 1024) {
  1681. return round($bytes/(1024), 1)."KB";
  1682. }
  1683. return $bytes."B";
  1684. };
  1685. $pid = posix_getpid();
  1686. $str = '';
  1687. reset(static::$_workers);
  1688. $current_worker = current(static::$_workers);
  1689. $default_worker_name = $current_worker->name;
  1690. /** @var \Workerman\Worker $worker */
  1691. foreach(TcpConnection::$connections as $connection) {
  1692. /** @var \Workerman\Connection\TcpConnection $connection */
  1693. $transport = $connection->transport;
  1694. $ipv4 = $connection->isIpV4() ? ' 1' : ' 0';
  1695. $ipv6 = $connection->isIpV6() ? ' 1' : ' 0';
  1696. $recv_q = $bytes_format($connection->getRecvBufferQueueSize());
  1697. $send_q = $bytes_format($connection->getSendBufferQueueSize());
  1698. $local_address = trim($connection->getLocalAddress());
  1699. $remote_address = trim($connection->getRemoteAddress());
  1700. $state = $connection->getStatus(false);
  1701. $bytes_read = $bytes_format($connection->bytesRead);
  1702. $bytes_written = $bytes_format($connection->bytesWritten);
  1703. $id = $connection->id;
  1704. $protocol = $connection->protocol ? $connection->protocol : $connection->transport;
  1705. $pos = strrpos($protocol, '\\');
  1706. if ($pos) {
  1707. $protocol = substr($protocol, $pos+1);
  1708. }
  1709. if (strlen($protocol) > 15) {
  1710. $protocol = substr($protocol, 0, 13) . '..';
  1711. }
  1712. $worker_name = isset($connection->worker) ? $connection->worker->name : $default_worker_name;
  1713. if (strlen($worker_name) > 14) {
  1714. $worker_name = substr($worker_name, 0, 12) . '..';
  1715. }
  1716. $str .= str_pad($pid, 9) . str_pad($worker_name, 16) . str_pad($id, 10) . str_pad($transport, 8)
  1717. . str_pad($protocol, 16) . str_pad($ipv4, 7) . str_pad($ipv6, 7) . str_pad($recv_q, 13)
  1718. . str_pad($send_q, 13) . str_pad($bytes_read, 13) . str_pad($bytes_written, 13) . ' '
  1719. . str_pad($state, 14) . ' ' . str_pad($local_address, 22) . ' ' . str_pad($remote_address, 22) ."\n";
  1720. }
  1721. if ($str) {
  1722. file_put_contents(static::$_statisticsFile, $str, FILE_APPEND);
  1723. }
  1724. }
  1725. /**
  1726. * Check errors when current process exited.
  1727. *
  1728. * @return void
  1729. */
  1730. public static function checkErrors()
  1731. {
  1732. if (static::STATUS_SHUTDOWN != static::$_status) {
  1733. $error_msg = static::$_OS === OS_TYPE_LINUX ? 'Worker['. posix_getpid() .'] process terminated' : 'Worker process terminated';
  1734. $errors = error_get_last();
  1735. if ($errors && ($errors['type'] === E_ERROR ||
  1736. $errors['type'] === E_PARSE ||
  1737. $errors['type'] === E_CORE_ERROR ||
  1738. $errors['type'] === E_COMPILE_ERROR ||
  1739. $errors['type'] === E_RECOVERABLE_ERROR)
  1740. ) {
  1741. $error_msg .= ' with ERROR: ' . static::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\"";
  1742. }
  1743. static::log($error_msg);
  1744. }
  1745. }
  1746. /**
  1747. * Get error message by error code.
  1748. *
  1749. * @param integer $type
  1750. * @return string
  1751. */
  1752. protected static function getErrorType($type)
  1753. {
  1754. switch ($type) {
  1755. case E_ERROR: // 1 //
  1756. return 'E_ERROR';
  1757. case E_WARNING: // 2 //
  1758. return 'E_WARNING';
  1759. case E_PARSE: // 4 //
  1760. return 'E_PARSE';
  1761. case E_NOTICE: // 8 //
  1762. return 'E_NOTICE';
  1763. case E_CORE_ERROR: // 16 //
  1764. return 'E_CORE_ERROR';
  1765. case E_CORE_WARNING: // 32 //
  1766. return 'E_CORE_WARNING';
  1767. case E_COMPILE_ERROR: // 64 //
  1768. return 'E_COMPILE_ERROR';
  1769. case E_COMPILE_WARNING: // 128 //
  1770. return 'E_COMPILE_WARNING';
  1771. case E_USER_ERROR: // 256 //
  1772. return 'E_USER_ERROR';
  1773. case E_USER_WARNING: // 512 //
  1774. return 'E_USER_WARNING';
  1775. case E_USER_NOTICE: // 1024 //
  1776. return 'E_USER_NOTICE';
  1777. case E_STRICT: // 2048 //
  1778. return 'E_STRICT';
  1779. case E_RECOVERABLE_ERROR: // 4096 //
  1780. return 'E_RECOVERABLE_ERROR';
  1781. case E_DEPRECATED: // 8192 //
  1782. return 'E_DEPRECATED';
  1783. case E_USER_DEPRECATED: // 16384 //
  1784. return 'E_USER_DEPRECATED';
  1785. }
  1786. return "";
  1787. }
  1788. /**
  1789. * Log.
  1790. *
  1791. * @param string $msg
  1792. * @return void
  1793. */
  1794. public static function log($msg)
  1795. {
  1796. $msg = $msg . "\n";
  1797. if (!static::$daemonize) {
  1798. static::safeEcho($msg);
  1799. }
  1800. file_put_contents((string)static::$logFile, date('Y-m-d H:i:s') . ' ' . 'pid:'
  1801. . (static::$_OS === OS_TYPE_LINUX ? posix_getpid() : 1) . ' ' . $msg, FILE_APPEND | LOCK_EX);
  1802. }
  1803. /**
  1804. * Safe Echo.
  1805. * @param $msg
  1806. * @param bool $decorated
  1807. * @return bool
  1808. */
  1809. public static function safeEcho($msg, $decorated = false)
  1810. {
  1811. $stream = static::outputStream();
  1812. if (!$stream) {
  1813. return false;
  1814. }
  1815. if (!$decorated) {
  1816. $line = $white = $green = $end = '';
  1817. if (static::$_outputDecorated) {
  1818. $line = "\033[1A\n\033[K";
  1819. $white = "\033[47;30m";
  1820. $green = "\033[32;40m";
  1821. $end = "\033[0m";
  1822. }
  1823. $msg = str_replace(array('<n>', '<w>', '<g>'), array($line, $white, $green), $msg);
  1824. $msg = str_replace(array('</n>', '</w>', '</g>'), $end, $msg);
  1825. } elseif (!static::$_outputDecorated) {
  1826. return false;
  1827. }
  1828. fwrite($stream, $msg);
  1829. fflush($stream);
  1830. return true;
  1831. }
  1832. /**
  1833. * @param null $stream
  1834. * @return bool|resource
  1835. */
  1836. private static function outputStream($stream = null)
  1837. {
  1838. if (!$stream) {
  1839. $stream = static::$_outputStream ? static::$_outputStream : STDOUT;
  1840. }
  1841. if (!$stream || !is_resource($stream) || 'stream' !== get_resource_type($stream)) {
  1842. return false;
  1843. }
  1844. $stat = fstat($stream);
  1845. if (($stat['mode'] & 0170000) === 0100000) {
  1846. // file
  1847. static::$_outputDecorated = false;
  1848. } else {
  1849. static::$_outputDecorated =
  1850. static::$_OS === OS_TYPE_LINUX &&
  1851. function_exists('posix_isatty') &&
  1852. posix_isatty($stream);
  1853. }
  1854. return static::$_outputStream = $stream;
  1855. }
  1856. /**
  1857. * Construct.
  1858. *
  1859. * @param string $socket_name
  1860. * @param array $context_option
  1861. */
  1862. public function __construct($socket_name = '', $context_option = array())
  1863. {
  1864. // Save all worker instances.
  1865. $this->workerId = spl_object_hash($this);
  1866. static::$_workers[$this->workerId] = $this;
  1867. static::$_pidMap[$this->workerId] = array();
  1868. // Get autoload root path.
  1869. $backtrace = debug_backtrace();
  1870. $this->_autoloadRootPath = dirname($backtrace[0]['file']);
  1871. // Context for socket.
  1872. if ($socket_name) {
  1873. $this->_socketName = $socket_name;
  1874. if (!isset($context_option['socket']['backlog'])) {
  1875. $context_option['socket']['backlog'] = static::DEFAULT_BACKLOG;
  1876. }
  1877. $this->_context = stream_context_create($context_option);
  1878. }
  1879. }
  1880. /**
  1881. * Listen.
  1882. *
  1883. * @throws Exception
  1884. */
  1885. public function listen()
  1886. {
  1887. if (!$this->_socketName) {
  1888. return;
  1889. }
  1890. // Autoload.
  1891. Autoloader::setRootPath($this->_autoloadRootPath);
  1892. if (!$this->_mainSocket) {
  1893. // Get the application layer communication protocol and listening address.
  1894. list($scheme, $address) = explode(':', $this->_socketName, 2);
  1895. // Check application layer protocol class.
  1896. if (!isset(static::$_builtinTransports[$scheme])) {
  1897. $scheme = ucfirst($scheme);
  1898. $this->protocol = substr($scheme,0,1)==='\\' ? $scheme : '\\Protocols\\' . $scheme;
  1899. if (!class_exists($this->protocol)) {
  1900. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  1901. if (!class_exists($this->protocol)) {
  1902. throw new Exception("class \\Protocols\\$scheme not exist");
  1903. }
  1904. }
  1905. if (!isset(static::$_builtinTransports[$this->transport])) {
  1906. throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
  1907. }
  1908. } else {
  1909. $this->transport = $scheme;
  1910. }
  1911. $local_socket = static::$_builtinTransports[$this->transport] . ":" . $address;
  1912. // Flag.
  1913. $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
  1914. $errno = 0;
  1915. $errmsg = '';
  1916. // SO_REUSEPORT.
  1917. if ($this->reusePort) {
  1918. stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
  1919. }
  1920. // Create an Internet or Unix domain server socket.
  1921. $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
  1922. if (!$this->_mainSocket) {
  1923. throw new Exception($errmsg);
  1924. }
  1925. if ($this->transport === 'ssl') {
  1926. stream_socket_enable_crypto($this->_mainSocket, false);
  1927. } elseif ($this->transport === 'unix') {
  1928. $socketFile = substr($address, 2);
  1929. if ($this->user) {
  1930. chown($socketFile, $this->user);
  1931. }
  1932. if ($this->group) {
  1933. chgrp($socketFile, $this->group);
  1934. }
  1935. }
  1936. // Try to open keepalive for tcp and disable Nagle algorithm.
  1937. if (function_exists('socket_import_stream') && static::$_builtinTransports[$this->transport] === 'tcp') {
  1938. set_error_handler(function(){});
  1939. $socket = socket_import_stream($this->_mainSocket);
  1940. socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  1941. socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
  1942. restore_error_handler();
  1943. }
  1944. // Non blocking.
  1945. stream_set_blocking($this->_mainSocket, 0);
  1946. }
  1947. $this->resumeAccept();
  1948. }
  1949. /**
  1950. * Unlisten.
  1951. *
  1952. * @return void
  1953. */
  1954. public function unlisten() {
  1955. $this->pauseAccept();
  1956. if ($this->_mainSocket) {
  1957. set_error_handler(function(){});
  1958. fclose($this->_mainSocket);
  1959. restore_error_handler();
  1960. $this->_mainSocket = null;
  1961. }
  1962. }
  1963. /**
  1964. * Pause accept new connections.
  1965. *
  1966. * @return void
  1967. */
  1968. public function pauseAccept()
  1969. {
  1970. if (static::$globalEvent && false === $this->_pauseAccept && $this->_mainSocket) {
  1971. static::$globalEvent->del($this->_mainSocket, EventInterface::EV_READ);
  1972. $this->_pauseAccept = true;
  1973. }
  1974. }
  1975. /**
  1976. * Resume accept new connections.
  1977. *
  1978. * @return void
  1979. */
  1980. public function resumeAccept()
  1981. {
  1982. // Register a listener to be notified when server socket is ready to read.
  1983. if (static::$globalEvent && true === $this->_pauseAccept && $this->_mainSocket) {
  1984. if ($this->transport !== 'udp') {
  1985. static::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
  1986. } else {
  1987. static::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1988. array($this, 'acceptUdpConnection'));
  1989. }
  1990. $this->_pauseAccept = false;
  1991. }
  1992. }
  1993. /**
  1994. * Get socket name.
  1995. *
  1996. * @return string
  1997. */
  1998. public function getSocketName()
  1999. {
  2000. return $this->_socketName ? lcfirst($this->_socketName) : 'none';
  2001. }
  2002. /**
  2003. * Run worker instance.
  2004. *
  2005. * @return void
  2006. */
  2007. public function run()
  2008. {
  2009. //Update process state.
  2010. static::$_status = static::STATUS_RUNNING;
  2011. // Register shutdown function for checking errors.
  2012. register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));
  2013. // Set autoload root path.
  2014. Autoloader::setRootPath($this->_autoloadRootPath);
  2015. // Create a global event loop.
  2016. if (!static::$globalEvent) {
  2017. $event_loop_class = static::getEventLoopName();
  2018. static::$globalEvent = new $event_loop_class;
  2019. $this->resumeAccept();
  2020. }
  2021. // Reinstall signal.
  2022. static::reinstallSignal();
  2023. // Init Timer.
  2024. Timer::init(static::$globalEvent);
  2025. // Set an empty onMessage callback.
  2026. if (empty($this->onMessage)) {
  2027. $this->onMessage = function () {};
  2028. }
  2029. // Try to emit onWorkerStart callback.
  2030. if ($this->onWorkerStart) {
  2031. try {
  2032. call_user_func($this->onWorkerStart, $this);
  2033. } catch (\Exception $e) {
  2034. static::log($e);
  2035. // Avoid rapid infinite loop exit.
  2036. sleep(1);
  2037. exit(250);
  2038. } catch (\Error $e) {
  2039. static::log($e);
  2040. // Avoid rapid infinite loop exit.
  2041. sleep(1);
  2042. exit(250);
  2043. }
  2044. }
  2045. restore_error_handler();
  2046. // Main loop.
  2047. static::$globalEvent->loop();
  2048. }
  2049. /**
  2050. * Stop current worker instance.
  2051. *
  2052. * @return void
  2053. */
  2054. public function stop()
  2055. {
  2056. // Try to emit onWorkerStop callback.
  2057. if ($this->onWorkerStop) {
  2058. try {
  2059. call_user_func($this->onWorkerStop, $this);
  2060. } catch (\Exception $e) {
  2061. static::log($e);
  2062. exit(250);
  2063. } catch (\Error $e) {
  2064. static::log($e);
  2065. exit(250);
  2066. }
  2067. }
  2068. // Remove listener for server socket.
  2069. $this->unlisten();
  2070. // Close all connections for the worker.
  2071. if (!static::$_gracefulStop) {
  2072. foreach ($this->connections as $connection) {
  2073. $connection->close();
  2074. }
  2075. }
  2076. // Clear callback.
  2077. $this->onMessage = $this->onClose = $this->onError = $this->onBufferDrain = $this->onBufferFull = null;
  2078. }
  2079. /**
  2080. * Accept a connection.
  2081. *
  2082. * @param resource $socket
  2083. * @return void
  2084. */
  2085. public function acceptConnection($socket)
  2086. {
  2087. // Accept a connection on server socket.
  2088. set_error_handler(function(){});
  2089. $new_socket = stream_socket_accept($socket, 0, $remote_address);
  2090. restore_error_handler();
  2091. // Thundering herd.
  2092. if (!$new_socket) {
  2093. return;
  2094. }
  2095. // TcpConnection.
  2096. $connection = new TcpConnection($new_socket, $remote_address);
  2097. $this->connections[$connection->id] = $connection;
  2098. $connection->worker = $this;
  2099. $connection->protocol = $this->protocol;
  2100. $connection->transport = $this->transport;
  2101. $connection->onMessage = $this->onMessage;
  2102. $connection->onClose = $this->onClose;
  2103. $connection->onError = $this->onError;
  2104. $connection->onBufferDrain = $this->onBufferDrain;
  2105. $connection->onBufferFull = $this->onBufferFull;
  2106. // Try to emit onConnect callback.
  2107. if ($this->onConnect) {
  2108. try {
  2109. call_user_func($this->onConnect, $connection);
  2110. } catch (\Exception $e) {
  2111. static::log($e);
  2112. exit(250);
  2113. } catch (\Error $e) {
  2114. static::log($e);
  2115. exit(250);
  2116. }
  2117. }
  2118. }
  2119. /**
  2120. * For udp package.
  2121. *
  2122. * @param resource $socket
  2123. * @return bool
  2124. */
  2125. public function acceptUdpConnection($socket)
  2126. {
  2127. set_error_handler(function(){});
  2128. $recv_buffer = stream_socket_recvfrom($socket, static::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
  2129. restore_error_handler();
  2130. if (false === $recv_buffer || empty($remote_address)) {
  2131. return false;
  2132. }
  2133. // UdpConnection.
  2134. $connection = new UdpConnection($socket, $remote_address);
  2135. $connection->protocol = $this->protocol;
  2136. if ($this->onMessage) {
  2137. try {
  2138. if ($this->protocol !== null) {
  2139. /** @var \Workerman\Protocols\ProtocolInterface $parser */
  2140. $parser = $this->protocol;
  2141. $recv_buffer = $parser::decode($recv_buffer, $connection);
  2142. // Discard bad packets.
  2143. if ($recv_buffer === false)
  2144. return true;
  2145. }
  2146. ConnectionInterface::$statistics['total_request']++;
  2147. call_user_func($this->onMessage, $connection, $recv_buffer);
  2148. } catch (\Exception $e) {
  2149. static::log($e);
  2150. exit(250);
  2151. } catch (\Error $e) {
  2152. static::log($e);
  2153. exit(250);
  2154. }
  2155. }
  2156. return true;
  2157. }
  2158. }