SqlBagOStuff.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. <?php
  2. /**
  3. * Object caching using a SQL database.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @ingroup Cache
  22. */
  23. use MediaWiki\MediaWikiServices;
  24. use Wikimedia\Rdbms\Database;
  25. use Wikimedia\Rdbms\IDatabase;
  26. use Wikimedia\Rdbms\DBError;
  27. use Wikimedia\Rdbms\DBQueryError;
  28. use Wikimedia\Rdbms\DBConnectionError;
  29. use Wikimedia\Rdbms\LoadBalancer;
  30. use Wikimedia\Rdbms\TransactionProfiler;
  31. use Wikimedia\WaitConditionLoop;
  32. /**
  33. * Class to store objects in the database
  34. *
  35. * @ingroup Cache
  36. */
  37. class SqlBagOStuff extends BagOStuff {
  38. /** @var array[] (server index => server config) */
  39. protected $serverInfos;
  40. /** @var string[] (server index => tag/host name) */
  41. protected $serverTags;
  42. /** @var int */
  43. protected $numServers;
  44. /** @var int */
  45. protected $lastExpireAll = 0;
  46. /** @var int */
  47. protected $purgePeriod = 100;
  48. /** @var int */
  49. protected $shards = 1;
  50. /** @var string */
  51. protected $tableName = 'objectcache';
  52. /** @var bool */
  53. protected $replicaOnly = false;
  54. /** @var int */
  55. protected $syncTimeout = 3;
  56. /** @var LoadBalancer|null */
  57. protected $separateMainLB;
  58. /** @var array */
  59. protected $conns;
  60. /** @var array UNIX timestamps */
  61. protected $connFailureTimes = [];
  62. /** @var array Exceptions */
  63. protected $connFailureErrors = [];
  64. /**
  65. * Constructor. Parameters are:
  66. * - server: A server info structure in the format required by each
  67. * element in $wgDBServers.
  68. *
  69. * - servers: An array of server info structures describing a set of database servers
  70. * to distribute keys to. If this is specified, the "server" option will be
  71. * ignored. If string keys are used, then they will be used for consistent
  72. * hashing *instead* of the host name (from the server config). This is useful
  73. * when a cluster is replicated to another site (with different host names)
  74. * but each server has a corresponding replica in the other cluster.
  75. *
  76. * - purgePeriod: The average number of object cache requests in between
  77. * garbage collection operations, where expired entries
  78. * are removed from the database. Or in other words, the
  79. * reciprocal of the probability of purging on any given
  80. * request. If this is set to zero, purging will never be
  81. * done.
  82. *
  83. * - tableName: The table name to use, default is "objectcache".
  84. *
  85. * - shards: The number of tables to use for data storage on each server.
  86. * If this is more than 1, table names will be formed in the style
  87. * objectcacheNNN where NNN is the shard index, between 0 and
  88. * shards-1. The number of digits will be the minimum number
  89. * required to hold the largest shard index. Data will be
  90. * distributed across all tables by key hash. This is for
  91. * MySQL bugs 61735 and 61736.
  92. * - slaveOnly: Whether to only use replica DBs and avoid triggering
  93. * garbage collection logic of expired items. This only
  94. * makes sense if the primary DB is used and only if get()
  95. * calls will be used. This is used by ReplicatedBagOStuff.
  96. * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
  97. *
  98. * @param array $params
  99. */
  100. public function __construct( $params ) {
  101. parent::__construct( $params );
  102. $this->attrMap[self::ATTR_EMULATION] = self::QOS_EMULATION_SQL;
  103. $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_NONE;
  104. if ( isset( $params['servers'] ) ) {
  105. $this->serverInfos = [];
  106. $this->serverTags = [];
  107. $this->numServers = count( $params['servers'] );
  108. $index = 0;
  109. foreach ( $params['servers'] as $tag => $info ) {
  110. $this->serverInfos[$index] = $info;
  111. if ( is_string( $tag ) ) {
  112. $this->serverTags[$index] = $tag;
  113. } else {
  114. $this->serverTags[$index] = $info['host'] ?? "#$index";
  115. }
  116. ++$index;
  117. }
  118. } elseif ( isset( $params['server'] ) ) {
  119. $this->serverInfos = [ $params['server'] ];
  120. $this->numServers = count( $this->serverInfos );
  121. } else {
  122. // Default to using the main wiki's database servers
  123. $this->serverInfos = false;
  124. $this->numServers = 1;
  125. $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_BE;
  126. }
  127. if ( isset( $params['purgePeriod'] ) ) {
  128. $this->purgePeriod = intval( $params['purgePeriod'] );
  129. }
  130. if ( isset( $params['tableName'] ) ) {
  131. $this->tableName = $params['tableName'];
  132. }
  133. if ( isset( $params['shards'] ) ) {
  134. $this->shards = intval( $params['shards'] );
  135. }
  136. if ( isset( $params['syncTimeout'] ) ) {
  137. $this->syncTimeout = $params['syncTimeout'];
  138. }
  139. $this->replicaOnly = !empty( $params['slaveOnly'] );
  140. }
  141. /**
  142. * Get a connection to the specified database
  143. *
  144. * @param int $serverIndex
  145. * @return Database
  146. * @throws MWException
  147. */
  148. protected function getDB( $serverIndex ) {
  149. if ( !isset( $this->conns[$serverIndex] ) ) {
  150. if ( $serverIndex >= $this->numServers ) {
  151. throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
  152. }
  153. # Don't keep timing out trying to connect for each call if the DB is down
  154. if ( isset( $this->connFailureErrors[$serverIndex] )
  155. && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
  156. ) {
  157. throw $this->connFailureErrors[$serverIndex];
  158. }
  159. if ( $this->serverInfos ) {
  160. // Use custom database defined by server connection info
  161. $info = $this->serverInfos[$serverIndex];
  162. $type = $info['type'] ?? 'mysql';
  163. $host = $info['host'] ?? '[unknown]';
  164. $this->logger->debug( __CLASS__ . ": connecting to $host" );
  165. // Use a blank trx profiler to ignore expections as this is a cache
  166. $info['trxProfiler'] = new TransactionProfiler();
  167. $db = Database::factory( $type, $info );
  168. $db->clearFlag( DBO_TRX ); // auto-commit mode
  169. } else {
  170. // Use the main LB database
  171. $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
  172. $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
  173. if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
  174. // Keep a separate connection to avoid contention and deadlocks
  175. $db = $lb->getConnection( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT );
  176. // @TODO: Use a blank trx profiler to ignore expections as this is a cache
  177. } else {
  178. // However, SQLite has the opposite behavior due to DB-level locking.
  179. // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
  180. $db = $lb->getConnection( $index );
  181. }
  182. }
  183. $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
  184. $this->conns[$serverIndex] = $db;
  185. }
  186. return $this->conns[$serverIndex];
  187. }
  188. /**
  189. * Get the server index and table name for a given key
  190. * @param string $key
  191. * @return array Server index and table name
  192. */
  193. protected function getTableByKey( $key ) {
  194. if ( $this->shards > 1 ) {
  195. $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
  196. $tableIndex = $hash % $this->shards;
  197. } else {
  198. $tableIndex = 0;
  199. }
  200. if ( $this->numServers > 1 ) {
  201. $sortedServers = $this->serverTags;
  202. ArrayUtils::consistentHashSort( $sortedServers, $key );
  203. reset( $sortedServers );
  204. $serverIndex = key( $sortedServers );
  205. } else {
  206. $serverIndex = 0;
  207. }
  208. return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
  209. }
  210. /**
  211. * Get the table name for a given shard index
  212. * @param int $index
  213. * @return string
  214. */
  215. protected function getTableNameByShard( $index ) {
  216. if ( $this->shards > 1 ) {
  217. $decimals = strlen( $this->shards - 1 );
  218. return $this->tableName .
  219. sprintf( "%0{$decimals}d", $index );
  220. } else {
  221. return $this->tableName;
  222. }
  223. }
  224. protected function doGet( $key, $flags = 0 ) {
  225. $casToken = null;
  226. return $this->getWithToken( $key, $casToken, $flags );
  227. }
  228. protected function getWithToken( $key, &$casToken, $flags = 0 ) {
  229. $values = $this->getMulti( [ $key ] );
  230. if ( array_key_exists( $key, $values ) ) {
  231. $casToken = $values[$key];
  232. return $values[$key];
  233. }
  234. return false;
  235. }
  236. public function getMulti( array $keys, $flags = 0 ) {
  237. $values = []; // array of (key => value)
  238. $keysByTable = [];
  239. foreach ( $keys as $key ) {
  240. list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
  241. $keysByTable[$serverIndex][$tableName][] = $key;
  242. }
  243. $this->garbageCollect(); // expire old entries if any
  244. $dataRows = [];
  245. foreach ( $keysByTable as $serverIndex => $serverKeys ) {
  246. try {
  247. $db = $this->getDB( $serverIndex );
  248. foreach ( $serverKeys as $tableName => $tableKeys ) {
  249. $res = $db->select( $tableName,
  250. [ 'keyname', 'value', 'exptime' ],
  251. [ 'keyname' => $tableKeys ],
  252. __METHOD__,
  253. // Approximate write-on-the-fly BagOStuff API via blocking.
  254. // This approximation fails if a ROLLBACK happens (which is rare).
  255. // We do not want to flush the TRX as that can break callers.
  256. $db->trxLevel() ? [ 'LOCK IN SHARE MODE' ] : []
  257. );
  258. if ( $res === false ) {
  259. continue;
  260. }
  261. foreach ( $res as $row ) {
  262. $row->serverIndex = $serverIndex;
  263. $row->tableName = $tableName;
  264. $dataRows[$row->keyname] = $row;
  265. }
  266. }
  267. } catch ( DBError $e ) {
  268. $this->handleReadError( $e, $serverIndex );
  269. }
  270. }
  271. foreach ( $keys as $key ) {
  272. if ( isset( $dataRows[$key] ) ) { // HIT?
  273. $row = $dataRows[$key];
  274. $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
  275. $db = null;
  276. try {
  277. $db = $this->getDB( $row->serverIndex );
  278. if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
  279. $this->debug( "get: key has expired" );
  280. } else { // HIT
  281. $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
  282. }
  283. } catch ( DBQueryError $e ) {
  284. $this->handleWriteError( $e, $db, $row->serverIndex );
  285. }
  286. } else { // MISS
  287. $this->debug( 'get: no matching rows' );
  288. }
  289. }
  290. return $values;
  291. }
  292. public function setMulti( array $data, $expiry = 0 ) {
  293. $keysByTable = [];
  294. foreach ( $data as $key => $value ) {
  295. list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
  296. $keysByTable[$serverIndex][$tableName][] = $key;
  297. }
  298. $this->garbageCollect(); // expire old entries if any
  299. $result = true;
  300. $exptime = (int)$expiry;
  301. foreach ( $keysByTable as $serverIndex => $serverKeys ) {
  302. $db = null;
  303. try {
  304. $db = $this->getDB( $serverIndex );
  305. } catch ( DBError $e ) {
  306. $this->handleWriteError( $e, $db, $serverIndex );
  307. $result = false;
  308. continue;
  309. }
  310. if ( $exptime < 0 ) {
  311. $exptime = 0;
  312. }
  313. if ( $exptime == 0 ) {
  314. $encExpiry = $this->getMaxDateTime( $db );
  315. } else {
  316. $exptime = $this->convertExpiry( $exptime );
  317. $encExpiry = $db->timestamp( $exptime );
  318. }
  319. foreach ( $serverKeys as $tableName => $tableKeys ) {
  320. $rows = [];
  321. foreach ( $tableKeys as $key ) {
  322. $rows[] = [
  323. 'keyname' => $key,
  324. 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
  325. 'exptime' => $encExpiry,
  326. ];
  327. }
  328. try {
  329. $db->replace(
  330. $tableName,
  331. [ 'keyname' ],
  332. $rows,
  333. __METHOD__
  334. );
  335. } catch ( DBError $e ) {
  336. $this->handleWriteError( $e, $db, $serverIndex );
  337. $result = false;
  338. }
  339. }
  340. }
  341. return $result;
  342. }
  343. public function set( $key, $value, $exptime = 0, $flags = 0 ) {
  344. $ok = $this->setMulti( [ $key => $value ], $exptime );
  345. if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
  346. $ok = $this->waitForReplication() && $ok;
  347. }
  348. return $ok;
  349. }
  350. protected function cas( $casToken, $key, $value, $exptime = 0 ) {
  351. list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
  352. $db = null;
  353. try {
  354. $db = $this->getDB( $serverIndex );
  355. $exptime = intval( $exptime );
  356. if ( $exptime < 0 ) {
  357. $exptime = 0;
  358. }
  359. if ( $exptime == 0 ) {
  360. $encExpiry = $this->getMaxDateTime( $db );
  361. } else {
  362. $exptime = $this->convertExpiry( $exptime );
  363. $encExpiry = $db->timestamp( $exptime );
  364. }
  365. // (T26425) use a replace if the db supports it instead of
  366. // delete/insert to avoid clashes with conflicting keynames
  367. $db->update(
  368. $tableName,
  369. [
  370. 'keyname' => $key,
  371. 'value' => $db->encodeBlob( $this->serialize( $value ) ),
  372. 'exptime' => $encExpiry
  373. ],
  374. [
  375. 'keyname' => $key,
  376. 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
  377. ],
  378. __METHOD__
  379. );
  380. } catch ( DBQueryError $e ) {
  381. $this->handleWriteError( $e, $db, $serverIndex );
  382. return false;
  383. }
  384. return (bool)$db->affectedRows();
  385. }
  386. public function delete( $key ) {
  387. list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
  388. $db = null;
  389. try {
  390. $db = $this->getDB( $serverIndex );
  391. $db->delete(
  392. $tableName,
  393. [ 'keyname' => $key ],
  394. __METHOD__ );
  395. } catch ( DBError $e ) {
  396. $this->handleWriteError( $e, $db, $serverIndex );
  397. return false;
  398. }
  399. return true;
  400. }
  401. public function incr( $key, $step = 1 ) {
  402. list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
  403. $db = null;
  404. try {
  405. $db = $this->getDB( $serverIndex );
  406. $step = intval( $step );
  407. $row = $db->selectRow(
  408. $tableName,
  409. [ 'value', 'exptime' ],
  410. [ 'keyname' => $key ],
  411. __METHOD__,
  412. [ 'FOR UPDATE' ] );
  413. if ( $row === false ) {
  414. // Missing
  415. return null;
  416. }
  417. $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__ );
  418. if ( $this->isExpired( $db, $row->exptime ) ) {
  419. // Expired, do not reinsert
  420. return null;
  421. }
  422. $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
  423. $newValue = $oldValue + $step;
  424. $db->insert( $tableName,
  425. [
  426. 'keyname' => $key,
  427. 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
  428. 'exptime' => $row->exptime
  429. ], __METHOD__, 'IGNORE' );
  430. if ( $db->affectedRows() == 0 ) {
  431. // Race condition. See T30611
  432. $newValue = null;
  433. }
  434. } catch ( DBError $e ) {
  435. $this->handleWriteError( $e, $db, $serverIndex );
  436. return null;
  437. }
  438. return $newValue;
  439. }
  440. public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
  441. $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
  442. if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
  443. $ok = $this->waitForReplication() && $ok;
  444. }
  445. return $ok;
  446. }
  447. public function changeTTL( $key, $expiry = 0 ) {
  448. list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
  449. $db = null;
  450. try {
  451. $db = $this->getDB( $serverIndex );
  452. $db->update(
  453. $tableName,
  454. [ 'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
  455. [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
  456. __METHOD__
  457. );
  458. if ( $db->affectedRows() == 0 ) {
  459. return false;
  460. }
  461. } catch ( DBError $e ) {
  462. $this->handleWriteError( $e, $db, $serverIndex );
  463. return false;
  464. }
  465. return true;
  466. }
  467. /**
  468. * @param IDatabase $db
  469. * @param string $exptime
  470. * @return bool
  471. */
  472. protected function isExpired( $db, $exptime ) {
  473. return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
  474. }
  475. /**
  476. * @param IDatabase $db
  477. * @return string
  478. */
  479. protected function getMaxDateTime( $db ) {
  480. if ( time() > 0x7fffffff ) {
  481. return $db->timestamp( 1 << 62 );
  482. } else {
  483. return $db->timestamp( 0x7fffffff );
  484. }
  485. }
  486. protected function garbageCollect() {
  487. if ( !$this->purgePeriod || $this->replicaOnly ) {
  488. // Disabled
  489. return;
  490. }
  491. // Only purge on one in every $this->purgePeriod requests.
  492. if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
  493. return;
  494. }
  495. $now = time();
  496. // Avoid repeating the delete within a few seconds
  497. if ( $now > ( $this->lastExpireAll + 1 ) ) {
  498. $this->lastExpireAll = $now;
  499. $this->expireAll();
  500. }
  501. }
  502. public function expireAll() {
  503. $this->deleteObjectsExpiringBefore( wfTimestampNow() );
  504. }
  505. /**
  506. * Delete objects from the database which expire before a certain date.
  507. * @param string $timestamp
  508. * @param bool|callable $progressCallback
  509. * @return bool
  510. */
  511. public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
  512. for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
  513. $db = null;
  514. try {
  515. $db = $this->getDB( $serverIndex );
  516. $dbTimestamp = $db->timestamp( $timestamp );
  517. $totalSeconds = false;
  518. $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
  519. for ( $i = 0; $i < $this->shards; $i++ ) {
  520. $maxExpTime = false;
  521. while ( true ) {
  522. $conds = $baseConds;
  523. if ( $maxExpTime !== false ) {
  524. $conds[] = 'exptime >= ' . $db->addQuotes( $maxExpTime );
  525. }
  526. $rows = $db->select(
  527. $this->getTableNameByShard( $i ),
  528. [ 'keyname', 'exptime' ],
  529. $conds,
  530. __METHOD__,
  531. [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
  532. if ( $rows === false || !$rows->numRows() ) {
  533. break;
  534. }
  535. $keys = [];
  536. $row = $rows->current();
  537. $minExpTime = $row->exptime;
  538. if ( $totalSeconds === false ) {
  539. $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
  540. - wfTimestamp( TS_UNIX, $minExpTime );
  541. }
  542. foreach ( $rows as $row ) {
  543. $keys[] = $row->keyname;
  544. $maxExpTime = $row->exptime;
  545. }
  546. $db->delete(
  547. $this->getTableNameByShard( $i ),
  548. [
  549. 'exptime >= ' . $db->addQuotes( $minExpTime ),
  550. 'exptime < ' . $db->addQuotes( $dbTimestamp ),
  551. 'keyname' => $keys
  552. ],
  553. __METHOD__ );
  554. if ( $progressCallback ) {
  555. if ( intval( $totalSeconds ) === 0 ) {
  556. $percent = 0;
  557. } else {
  558. $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
  559. - wfTimestamp( TS_UNIX, $maxExpTime );
  560. if ( $remainingSeconds > $totalSeconds ) {
  561. $totalSeconds = $remainingSeconds;
  562. }
  563. $processedSeconds = $totalSeconds - $remainingSeconds;
  564. $percent = ( $i + $processedSeconds / $totalSeconds )
  565. / $this->shards * 100;
  566. }
  567. $percent = ( $percent / $this->numServers )
  568. + ( $serverIndex / $this->numServers * 100 );
  569. call_user_func( $progressCallback, $percent );
  570. }
  571. }
  572. }
  573. } catch ( DBError $e ) {
  574. $this->handleWriteError( $e, $db, $serverIndex );
  575. return false;
  576. }
  577. }
  578. return true;
  579. }
  580. /**
  581. * Delete content of shard tables in every server.
  582. * Return true if the operation is successful, false otherwise.
  583. * @return bool
  584. */
  585. public function deleteAll() {
  586. for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
  587. $db = null;
  588. try {
  589. $db = $this->getDB( $serverIndex );
  590. for ( $i = 0; $i < $this->shards; $i++ ) {
  591. $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
  592. }
  593. } catch ( DBError $e ) {
  594. $this->handleWriteError( $e, $db, $serverIndex );
  595. return false;
  596. }
  597. }
  598. return true;
  599. }
  600. /**
  601. * Serialize an object and, if possible, compress the representation.
  602. * On typical message and page data, this can provide a 3X decrease
  603. * in storage requirements.
  604. *
  605. * @param mixed &$data
  606. * @return string
  607. */
  608. protected function serialize( &$data ) {
  609. $serial = serialize( $data );
  610. if ( function_exists( 'gzdeflate' ) ) {
  611. return gzdeflate( $serial );
  612. } else {
  613. return $serial;
  614. }
  615. }
  616. /**
  617. * Unserialize and, if necessary, decompress an object.
  618. * @param string $serial
  619. * @return mixed
  620. */
  621. protected function unserialize( $serial ) {
  622. if ( function_exists( 'gzinflate' ) ) {
  623. Wikimedia\suppressWarnings();
  624. $decomp = gzinflate( $serial );
  625. Wikimedia\restoreWarnings();
  626. if ( false !== $decomp ) {
  627. $serial = $decomp;
  628. }
  629. }
  630. $ret = unserialize( $serial );
  631. return $ret;
  632. }
  633. /**
  634. * Handle a DBError which occurred during a read operation.
  635. *
  636. * @param DBError $exception
  637. * @param int $serverIndex
  638. */
  639. protected function handleReadError( DBError $exception, $serverIndex ) {
  640. if ( $exception instanceof DBConnectionError ) {
  641. $this->markServerDown( $exception, $serverIndex );
  642. }
  643. $this->logger->error( "DBError: {$exception->getMessage()}" );
  644. if ( $exception instanceof DBConnectionError ) {
  645. $this->setLastError( BagOStuff::ERR_UNREACHABLE );
  646. $this->logger->debug( __METHOD__ . ": ignoring connection error" );
  647. } else {
  648. $this->setLastError( BagOStuff::ERR_UNEXPECTED );
  649. $this->logger->debug( __METHOD__ . ": ignoring query error" );
  650. }
  651. }
  652. /**
  653. * Handle a DBQueryError which occurred during a write operation.
  654. *
  655. * @param DBError $exception
  656. * @param IDatabase|null $db DB handle or null if connection failed
  657. * @param int $serverIndex
  658. * @throws Exception
  659. */
  660. protected function handleWriteError( DBError $exception, IDatabase $db = null, $serverIndex ) {
  661. if ( !$db ) {
  662. $this->markServerDown( $exception, $serverIndex );
  663. } elseif ( $db->wasReadOnlyError() ) {
  664. if ( $db->trxLevel() && $this->usesMainDB() ) {
  665. // Errors like deadlocks and connection drops already cause rollback.
  666. // For consistency, we have no choice but to throw an error and trigger
  667. // complete rollback if the main DB is also being used as the cache DB.
  668. throw $exception;
  669. }
  670. }
  671. $this->logger->error( "DBError: {$exception->getMessage()}" );
  672. if ( $exception instanceof DBConnectionError ) {
  673. $this->setLastError( BagOStuff::ERR_UNREACHABLE );
  674. $this->logger->debug( __METHOD__ . ": ignoring connection error" );
  675. } else {
  676. $this->setLastError( BagOStuff::ERR_UNEXPECTED );
  677. $this->logger->debug( __METHOD__ . ": ignoring query error" );
  678. }
  679. }
  680. /**
  681. * Mark a server down due to a DBConnectionError exception
  682. *
  683. * @param DBError $exception
  684. * @param int $serverIndex
  685. */
  686. protected function markServerDown( DBError $exception, $serverIndex ) {
  687. unset( $this->conns[$serverIndex] ); // bug T103435
  688. if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
  689. if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
  690. unset( $this->connFailureTimes[$serverIndex] );
  691. unset( $this->connFailureErrors[$serverIndex] );
  692. } else {
  693. $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
  694. return;
  695. }
  696. }
  697. $now = time();
  698. $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
  699. $this->connFailureTimes[$serverIndex] = $now;
  700. $this->connFailureErrors[$serverIndex] = $exception;
  701. }
  702. /**
  703. * Create shard tables. For use from eval.php.
  704. */
  705. public function createTables() {
  706. for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
  707. $db = $this->getDB( $serverIndex );
  708. if ( $db->getType() !== 'mysql' ) {
  709. throw new MWException( __METHOD__ . ' is not supported on this DB server' );
  710. }
  711. for ( $i = 0; $i < $this->shards; $i++ ) {
  712. $db->query(
  713. 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
  714. ' LIKE ' . $db->tableName( 'objectcache' ),
  715. __METHOD__ );
  716. }
  717. }
  718. }
  719. /**
  720. * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
  721. */
  722. protected function usesMainDB() {
  723. return !$this->serverInfos;
  724. }
  725. protected function waitForReplication() {
  726. if ( !$this->usesMainDB() ) {
  727. // Custom DB server list; probably doesn't use replication
  728. return true;
  729. }
  730. $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
  731. if ( $lb->getServerCount() <= 1 ) {
  732. return true; // no replica DBs
  733. }
  734. // Main LB is used; wait for any replica DBs to catch up
  735. $masterPos = $lb->getMasterPos();
  736. if ( !$masterPos ) {
  737. return true; // not applicable
  738. }
  739. $loop = new WaitConditionLoop(
  740. function () use ( $lb, $masterPos ) {
  741. return $lb->waitForAll( $masterPos, 1 );
  742. },
  743. $this->syncTimeout,
  744. $this->busyCallbacks
  745. );
  746. return ( $loop->invoke() === $loop::CONDITION_REACHED );
  747. }
  748. }