ReplicationGui.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. <?php
  2. /**
  3. * Functions for the replication GUI
  4. */
  5. declare(strict_types=1);
  6. namespace PhpMyAdmin;
  7. use PhpMyAdmin\Query\Utilities;
  8. use function htmlspecialchars;
  9. use function in_array;
  10. use function is_array;
  11. use function mb_strrpos;
  12. use function mb_strtolower;
  13. use function mb_substr;
  14. use function sprintf;
  15. use function str_replace;
  16. use function strlen;
  17. use function strtok;
  18. use function time;
  19. /**
  20. * Functions for the replication GUI
  21. */
  22. class ReplicationGui
  23. {
  24. /** @var Replication */
  25. private $replication;
  26. /** @var Template */
  27. private $template;
  28. /**
  29. * @param Replication $replication Replication instance
  30. * @param Template $template Template instance
  31. */
  32. public function __construct(Replication $replication, Template $template)
  33. {
  34. $this->replication = $replication;
  35. $this->template = $template;
  36. }
  37. /**
  38. * returns HTML for error message
  39. *
  40. * @return string HTML code
  41. */
  42. public function getHtmlForErrorMessage()
  43. {
  44. $html = '';
  45. if (isset($_SESSION['replication']['sr_action_status'], $_SESSION['replication']['sr_action_info'])) {
  46. if ($_SESSION['replication']['sr_action_status'] === 'error') {
  47. $error_message = $_SESSION['replication']['sr_action_info'];
  48. $html .= Message::error($error_message)->getDisplay();
  49. $_SESSION['replication']['sr_action_status'] = 'unknown';
  50. } elseif ($_SESSION['replication']['sr_action_status'] === 'success') {
  51. $success_message = $_SESSION['replication']['sr_action_info'];
  52. $html .= Message::success($success_message)->getDisplay();
  53. $_SESSION['replication']['sr_action_status'] = 'unknown';
  54. }
  55. }
  56. return $html;
  57. }
  58. /**
  59. * returns HTML for master replication
  60. *
  61. * @return string HTML code
  62. */
  63. public function getHtmlForMasterReplication()
  64. {
  65. global $dbi;
  66. if (! isset($_POST['repl_clear_scr'])) {
  67. $masterStatusTable = $this->getHtmlForReplicationStatusTable('master', true, false);
  68. $slaves = $dbi->fetchResult('SHOW SLAVE HOSTS', null, null);
  69. $urlParams = $GLOBALS['url_params'];
  70. $urlParams['mr_adduser'] = true;
  71. $urlParams['repl_clear_scr'] = true;
  72. }
  73. if (isset($_POST['mr_adduser'])) {
  74. $masterAddSlaveUser = $this->getHtmlForReplicationMasterAddSlaveUser();
  75. }
  76. return $this->template->render('server/replication/master_replication', [
  77. 'clear_screen' => isset($_POST['repl_clear_scr']),
  78. 'master_status_table' => $masterStatusTable ?? '',
  79. 'slaves' => $slaves ?? [],
  80. 'url_params' => $urlParams ?? [],
  81. 'master_add_user' => isset($_POST['mr_adduser']),
  82. 'master_add_slave_user' => $masterAddSlaveUser ?? '',
  83. ]);
  84. }
  85. /**
  86. * returns HTML for master replication configuration
  87. *
  88. * @return string HTML code
  89. */
  90. public function getHtmlForMasterConfiguration()
  91. {
  92. $databaseMultibox = $this->getHtmlForReplicationDbMultibox();
  93. return $this->template->render(
  94. 'server/replication/master_configuration',
  95. ['database_multibox' => $databaseMultibox]
  96. );
  97. }
  98. /**
  99. * returns HTML for slave replication configuration
  100. *
  101. * @param bool $serverSlaveStatus Whether it is Master or Slave
  102. * @param array $serverSlaveReplication Slave replication
  103. *
  104. * @return string HTML code
  105. */
  106. public function getHtmlForSlaveConfiguration(
  107. $serverSlaveStatus,
  108. array $serverSlaveReplication
  109. ) {
  110. global $dbi;
  111. $serverSlaveMultiReplication = $dbi->fetchResult(
  112. 'SHOW ALL SLAVES STATUS'
  113. );
  114. if ($serverSlaveStatus) {
  115. $urlParams = $GLOBALS['url_params'];
  116. $urlParams['sr_take_action'] = true;
  117. $urlParams['sr_slave_server_control'] = true;
  118. if ($serverSlaveReplication[0]['Slave_IO_Running'] === 'No') {
  119. $urlParams['sr_slave_action'] = 'start';
  120. } else {
  121. $urlParams['sr_slave_action'] = 'stop';
  122. }
  123. $urlParams['sr_slave_control_parm'] = 'IO_THREAD';
  124. $slaveControlIoLink = Url::getCommon($urlParams, '');
  125. if ($serverSlaveReplication[0]['Slave_SQL_Running'] === 'No') {
  126. $urlParams['sr_slave_action'] = 'start';
  127. } else {
  128. $urlParams['sr_slave_action'] = 'stop';
  129. }
  130. $urlParams['sr_slave_control_parm'] = 'SQL_THREAD';
  131. $slaveControlSqlLink = Url::getCommon($urlParams, '');
  132. if ($serverSlaveReplication[0]['Slave_IO_Running'] === 'No'
  133. || $serverSlaveReplication[0]['Slave_SQL_Running'] === 'No'
  134. ) {
  135. $urlParams['sr_slave_action'] = 'start';
  136. } else {
  137. $urlParams['sr_slave_action'] = 'stop';
  138. }
  139. $urlParams['sr_slave_control_parm'] = null;
  140. $slaveControlFullLink = Url::getCommon($urlParams, '');
  141. $urlParams['sr_slave_action'] = 'reset';
  142. $slaveControlResetLink = Url::getCommon($urlParams, '');
  143. $urlParams = $GLOBALS['url_params'];
  144. $urlParams['sr_take_action'] = true;
  145. $urlParams['sr_slave_skip_error'] = true;
  146. $slaveSkipErrorLink = Url::getCommon($urlParams, '');
  147. $urlParams = $GLOBALS['url_params'];
  148. $urlParams['sl_configure'] = true;
  149. $urlParams['repl_clear_scr'] = true;
  150. $reconfigureMasterLink = Url::getCommon($urlParams, '');
  151. $slaveStatusTable = $this->getHtmlForReplicationStatusTable('slave', true, false);
  152. $slaveIoRunning = $serverSlaveReplication[0]['Slave_IO_Running'] !== 'No';
  153. $slaveSqlRunning = $serverSlaveReplication[0]['Slave_SQL_Running'] !== 'No';
  154. }
  155. return $this->template->render('server/replication/slave_configuration', [
  156. 'server_slave_multi_replication' => $serverSlaveMultiReplication,
  157. 'url_params' => $GLOBALS['url_params'],
  158. 'master_connection' => $_POST['master_connection'] ?? '',
  159. 'server_slave_status' => $serverSlaveStatus,
  160. 'slave_status_table' => $slaveStatusTable ?? '',
  161. 'slave_sql_running' => $slaveSqlRunning ?? false,
  162. 'slave_io_running' => $slaveIoRunning ?? false,
  163. 'slave_control_full_link' => $slaveControlFullLink ?? '',
  164. 'slave_control_reset_link' => $slaveControlResetLink ?? '',
  165. 'slave_control_sql_link' => $slaveControlSqlLink ?? '',
  166. 'slave_control_io_link' => $slaveControlIoLink ?? '',
  167. 'slave_skip_error_link' => $slaveSkipErrorLink ?? '',
  168. 'reconfigure_master_link' => $reconfigureMasterLink ?? '',
  169. 'has_slave_configure' => isset($_POST['sl_configure']),
  170. ]);
  171. }
  172. /**
  173. * returns HTML code for selecting databases
  174. *
  175. * @return string HTML code
  176. */
  177. public function getHtmlForReplicationDbMultibox()
  178. {
  179. $databases = [];
  180. foreach ($GLOBALS['dblist']->databases as $database) {
  181. if (Utilities::isSystemSchema($database)) {
  182. continue;
  183. }
  184. $databases[] = $database;
  185. }
  186. return $this->template->render('server/replication/database_multibox', ['databases' => $databases]);
  187. }
  188. /**
  189. * returns HTML for changing master
  190. *
  191. * @param string $submitName submit button name
  192. *
  193. * @return string HTML code
  194. */
  195. public function getHtmlForReplicationChangeMaster($submitName)
  196. {
  197. [
  198. $usernameLength,
  199. $hostnameLength,
  200. ] = $this->getUsernameHostnameLength();
  201. return $this->template->render('server/replication/change_master', [
  202. 'server_id' => time(),
  203. 'username_length' => $usernameLength,
  204. 'hostname_length' => $hostnameLength,
  205. 'submit_name' => $submitName,
  206. ]);
  207. }
  208. /**
  209. * This function returns html code for table with replication status.
  210. *
  211. * @param string $type either master or slave
  212. * @param bool $isHidden if true, then default style is set to hidden,
  213. * default value false
  214. * @param bool $hasTitle if true, then title is displayed, default true
  215. *
  216. * @return string HTML code
  217. */
  218. public function getHtmlForReplicationStatusTable(
  219. $type,
  220. $isHidden = false,
  221. $hasTitle = true
  222. ): string {
  223. global $dbi;
  224. $replicationInfo = new ReplicationInfo($dbi);
  225. $replicationInfo->load($_POST['master_connection'] ?? null);
  226. $replicationVariables = $replicationInfo->primaryVariables;
  227. $variablesAlerts = null;
  228. $variablesOks = null;
  229. $serverReplication = $replicationInfo->getPrimaryStatus();
  230. if ($type === 'slave') {
  231. $replicationVariables = $replicationInfo->replicaVariables;
  232. $variablesAlerts = [
  233. 'Slave_IO_Running' => 'No',
  234. 'Slave_SQL_Running' => 'No',
  235. ];
  236. $variablesOks = [
  237. 'Slave_IO_Running' => 'Yes',
  238. 'Slave_SQL_Running' => 'Yes',
  239. ];
  240. $serverReplication = $replicationInfo->getReplicaStatus();
  241. }
  242. $variables = [];
  243. foreach ($replicationVariables as $variable) {
  244. $serverReplicationVariable = is_array($serverReplication) && isset($serverReplication[0])
  245. ? $serverReplication[0][$variable]
  246. : '';
  247. $variables[$variable] = [
  248. 'name' => $variable,
  249. 'status' => '',
  250. 'value' => $serverReplicationVariable,
  251. ];
  252. if (isset($variablesAlerts[$variable])
  253. && $variablesAlerts[$variable] === $serverReplicationVariable
  254. ) {
  255. $variables[$variable]['status'] = 'attention';
  256. } elseif (isset($variablesOks[$variable])
  257. && $variablesOks[$variable] === $serverReplicationVariable
  258. ) {
  259. $variables[$variable]['status'] = 'allfine';
  260. }
  261. $variablesWrap = [
  262. 'Replicate_Do_DB',
  263. 'Replicate_Ignore_DB',
  264. 'Replicate_Do_Table',
  265. 'Replicate_Ignore_Table',
  266. 'Replicate_Wild_Do_Table',
  267. 'Replicate_Wild_Ignore_Table',
  268. ];
  269. if (! in_array($variable, $variablesWrap)) {
  270. continue;
  271. }
  272. $variables[$variable]['value'] = str_replace(
  273. ',',
  274. ', ',
  275. $serverReplicationVariable
  276. );
  277. }
  278. return $this->template->render('server/replication/status_table', [
  279. 'type' => $type,
  280. 'is_hidden' => $isHidden,
  281. 'has_title' => $hasTitle,
  282. 'variables' => $variables,
  283. ]);
  284. }
  285. /**
  286. * get the correct username and hostname lengths for this MySQL server
  287. *
  288. * @return array username length, hostname length
  289. */
  290. public function getUsernameHostnameLength()
  291. {
  292. global $dbi;
  293. $fields_info = $dbi->getColumns('mysql', 'user');
  294. $username_length = 16;
  295. $hostname_length = 41;
  296. foreach ($fields_info as $val) {
  297. if ($val['Field'] === 'User') {
  298. strtok($val['Type'], '()');
  299. $v = strtok('()');
  300. if (Util::isInteger($v)) {
  301. $username_length = (int) $v;
  302. }
  303. } elseif ($val['Field'] === 'Host') {
  304. strtok($val['Type'], '()');
  305. $v = strtok('()');
  306. if (Util::isInteger($v)) {
  307. $hostname_length = (int) $v;
  308. }
  309. }
  310. }
  311. return [
  312. $username_length,
  313. $hostname_length,
  314. ];
  315. }
  316. /**
  317. * returns html code to add a replication slave user to the master
  318. *
  319. * @return string HTML code
  320. */
  321. public function getHtmlForReplicationMasterAddSlaveUser()
  322. {
  323. global $dbi;
  324. [
  325. $usernameLength,
  326. $hostnameLength,
  327. ] = $this->getUsernameHostnameLength();
  328. if (isset($_POST['username']) && strlen($_POST['username']) === 0) {
  329. $GLOBALS['pred_username'] = 'any';
  330. }
  331. $username = '';
  332. if (! empty($_POST['username'])) {
  333. $username = $GLOBALS['new_username'] ?? $_POST['username'];
  334. }
  335. $currentUser = $dbi->fetchValue('SELECT USER();');
  336. if (! empty($currentUser)) {
  337. $userHost = str_replace(
  338. "'",
  339. '',
  340. mb_substr(
  341. $currentUser,
  342. mb_strrpos($currentUser, '@') + 1
  343. )
  344. );
  345. if ($userHost !== 'localhost' && $userHost !== '127.0.0.1') {
  346. $thisHost = $userHost;
  347. }
  348. }
  349. // when we start editing a user, $GLOBALS['pred_hostname'] is not defined
  350. if (! isset($GLOBALS['pred_hostname']) && isset($_POST['hostname'])) {
  351. switch (mb_strtolower($_POST['hostname'])) {
  352. case 'localhost':
  353. case '127.0.0.1':
  354. $GLOBALS['pred_hostname'] = 'localhost';
  355. break;
  356. case '%':
  357. $GLOBALS['pred_hostname'] = 'any';
  358. break;
  359. default:
  360. $GLOBALS['pred_hostname'] = 'userdefined';
  361. break;
  362. }
  363. }
  364. return $this->template->render('server/replication/master_add_slave_user', [
  365. 'username_length' => $usernameLength,
  366. 'hostname_length' => $hostnameLength,
  367. 'has_username' => isset($_POST['username']),
  368. 'username' => $username,
  369. 'hostname' => $_POST['hostname'] ?? '',
  370. 'predefined_username' => $GLOBALS['pred_username'] ?? '',
  371. 'predefined_hostname' => $GLOBALS['pred_hostname'] ?? '',
  372. 'this_host' => $thisHost ?? null,
  373. ]);
  374. }
  375. /**
  376. * handle control requests
  377. *
  378. * @return void
  379. */
  380. public function handleControlRequest()
  381. {
  382. if (! isset($_POST['sr_take_action'])) {
  383. return;
  384. }
  385. $refresh = false;
  386. $result = false;
  387. $messageSuccess = '';
  388. $messageError = '';
  389. if (isset($_POST['slave_changemaster']) && ! $GLOBALS['cfg']['AllowArbitraryServer']) {
  390. $_SESSION['replication']['sr_action_status'] = 'error';
  391. $_SESSION['replication']['sr_action_info'] = __(
  392. 'Connection to server is disabled, please enable'
  393. . ' $cfg[\'AllowArbitraryServer\'] in phpMyAdmin configuration.'
  394. );
  395. } elseif (isset($_POST['slave_changemaster'])) {
  396. $result = $this->handleRequestForSlaveChangeMaster();
  397. } elseif (isset($_POST['sr_slave_server_control'])) {
  398. $result = $this->handleRequestForSlaveServerControl();
  399. $refresh = true;
  400. switch ($_POST['sr_slave_action']) {
  401. case 'start':
  402. $messageSuccess = __('Replication started successfully.');
  403. $messageError = __('Error starting replication.');
  404. break;
  405. case 'stop':
  406. $messageSuccess = __('Replication stopped successfully.');
  407. $messageError = __('Error stopping replication.');
  408. break;
  409. case 'reset':
  410. $messageSuccess = __('Replication resetting successfully.');
  411. $messageError = __('Error resetting replication.');
  412. break;
  413. default:
  414. $messageSuccess = __('Success.');
  415. $messageError = __('Error.');
  416. break;
  417. }
  418. } elseif (isset($_POST['sr_slave_skip_error'])) {
  419. $result = $this->handleRequestForSlaveSkipError();
  420. }
  421. if ($refresh) {
  422. $response = Response::getInstance();
  423. if ($response->isAjax()) {
  424. $response->setRequestStatus($result);
  425. $response->addJSON(
  426. 'message',
  427. $result
  428. ? Message::success($messageSuccess)
  429. : Message::error($messageError)
  430. );
  431. } else {
  432. Core::sendHeaderLocation(
  433. './index.php?route=/server/replication'
  434. . Url::getCommonRaw($GLOBALS['url_params'], '&')
  435. );
  436. }
  437. }
  438. unset($refresh);
  439. }
  440. /**
  441. * handle control requests for Slave Change Master
  442. *
  443. * @return bool
  444. */
  445. public function handleRequestForSlaveChangeMaster()
  446. {
  447. /** @var DatabaseInterface $dbi */
  448. global $dbi;
  449. $sr = [
  450. 'username' => $dbi->escapeString($_POST['username']),
  451. 'pma_pw' => $dbi->escapeString($_POST['pma_pw']),
  452. 'hostname' => $dbi->escapeString($_POST['hostname']),
  453. 'port' => (int) $dbi->escapeString($_POST['text_port']),
  454. ];
  455. $_SESSION['replication']['m_username'] = $sr['username'];
  456. $_SESSION['replication']['m_password'] = $sr['pma_pw'];
  457. $_SESSION['replication']['m_hostname'] = $sr['hostname'];
  458. $_SESSION['replication']['m_port'] = $sr['port'];
  459. $_SESSION['replication']['m_correct'] = '';
  460. $_SESSION['replication']['sr_action_status'] = 'error';
  461. $_SESSION['replication']['sr_action_info'] = __('Unknown error');
  462. // Attempt to connect to the new master server
  463. $link_to_master = $this->replication->connectToMaster(
  464. $sr['username'],
  465. $sr['pma_pw'],
  466. $sr['hostname'],
  467. $sr['port']
  468. );
  469. if (! $link_to_master) {
  470. $_SESSION['replication']['sr_action_status'] = 'error';
  471. $_SESSION['replication']['sr_action_info'] = sprintf(
  472. __('Unable to connect to master %s.'),
  473. htmlspecialchars($sr['hostname'])
  474. );
  475. } else {
  476. // Read the current master position
  477. $position = $this->replication->slaveBinLogMaster(DatabaseInterface::CONNECT_AUXILIARY);
  478. if (empty($position)) {
  479. $_SESSION['replication']['sr_action_status'] = 'error';
  480. $_SESSION['replication']['sr_action_info']
  481. = __(
  482. 'Unable to read master log position. '
  483. . 'Possible privilege problem on master.'
  484. );
  485. } else {
  486. $_SESSION['replication']['m_correct'] = true;
  487. if (! $this->replication->slaveChangeMaster(
  488. $sr['username'],
  489. $sr['pma_pw'],
  490. $sr['hostname'],
  491. $sr['port'],
  492. $position,
  493. true,
  494. false,
  495. DatabaseInterface::CONNECT_USER
  496. )
  497. ) {
  498. $_SESSION['replication']['sr_action_status'] = 'error';
  499. $_SESSION['replication']['sr_action_info']
  500. = __('Unable to change master!');
  501. } else {
  502. $_SESSION['replication']['sr_action_status'] = 'success';
  503. $_SESSION['replication']['sr_action_info'] = sprintf(
  504. __('Master server changed successfully to %s.'),
  505. htmlspecialchars($sr['hostname'])
  506. );
  507. }
  508. }
  509. }
  510. return $_SESSION['replication']['sr_action_status'] === 'success';
  511. }
  512. /**
  513. * handle control requests for Slave Server Control
  514. *
  515. * @return bool
  516. */
  517. public function handleRequestForSlaveServerControl()
  518. {
  519. global $dbi;
  520. if (empty($_POST['sr_slave_control_parm'])) {
  521. $_POST['sr_slave_control_parm'] = null;
  522. }
  523. if ($_POST['sr_slave_action'] === 'reset') {
  524. $qStop = $this->replication->slaveControl('STOP', null, DatabaseInterface::CONNECT_USER);
  525. $qReset = $dbi->tryQuery('RESET SLAVE;');
  526. $qStart = $this->replication->slaveControl('START', null, DatabaseInterface::CONNECT_USER);
  527. $result = $qStop !== false && $qStop !== -1 &&
  528. $qReset !== false && $qReset !== -1 &&
  529. $qStart !== false && $qStart !== -1;
  530. } else {
  531. $qControl = $this->replication->slaveControl(
  532. $_POST['sr_slave_action'],
  533. $_POST['sr_slave_control_parm'],
  534. DatabaseInterface::CONNECT_USER
  535. );
  536. $result = $qControl !== false && $qControl !== -1;
  537. }
  538. return $result;
  539. }
  540. /**
  541. * handle control requests for Slave Skip Error
  542. *
  543. * @return bool
  544. */
  545. public function handleRequestForSlaveSkipError()
  546. {
  547. global $dbi;
  548. $count = 1;
  549. if (isset($_POST['sr_skip_errors_count'])) {
  550. $count = $_POST['sr_skip_errors_count'] * 1;
  551. }
  552. $qStop = $this->replication->slaveControl('STOP', null, DatabaseInterface::CONNECT_USER);
  553. $qSkip = $dbi->tryQuery(
  554. 'SET GLOBAL SQL_SLAVE_SKIP_COUNTER = ' . $count . ';'
  555. );
  556. $qStart = $this->replication->slaveControl('START', null, DatabaseInterface::CONNECT_USER);
  557. return $qStop !== false && $qStop !== -1 &&
  558. $qSkip !== false && $qSkip !== -1 &&
  559. $qStart !== false && $qStart !== -1;
  560. }
  561. }