SqlBagOStuff.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  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\AtEase\AtEase;
  25. use Wikimedia\Rdbms\Database;
  26. use Wikimedia\Rdbms\IDatabase;
  27. use Wikimedia\Rdbms\DBError;
  28. use Wikimedia\Rdbms\DBQueryError;
  29. use Wikimedia\Rdbms\DBConnectionError;
  30. use Wikimedia\Rdbms\IMaintainableDatabase;
  31. use Wikimedia\Rdbms\LoadBalancer;
  32. use Wikimedia\ScopedCallback;
  33. use Wikimedia\Timestamp\ConvertibleTimestamp;
  34. use Wikimedia\WaitConditionLoop;
  35. /**
  36. * Class to store objects in the database
  37. *
  38. * @ingroup Cache
  39. */
  40. class SqlBagOStuff extends MediumSpecificBagOStuff {
  41. /** @var array[] (server index => server config) */
  42. protected $serverInfos;
  43. /** @var string[] (server index => tag/host name) */
  44. protected $serverTags;
  45. /** @var int */
  46. protected $numServerShards;
  47. /** @var int UNIX timestamp */
  48. protected $lastGarbageCollect = 0;
  49. /** @var int */
  50. protected $purgePeriod = 10;
  51. /** @var int */
  52. protected $purgeLimit = 100;
  53. /** @var int */
  54. protected $numTableShards = 1;
  55. /** @var string */
  56. protected $tableName = 'objectcache';
  57. /** @var bool */
  58. protected $replicaOnly = false;
  59. /** @var LoadBalancer|null */
  60. protected $separateMainLB;
  61. /** @var array */
  62. protected $conns;
  63. /** @var array UNIX timestamps */
  64. protected $connFailureTimes = [];
  65. /** @var array Exceptions */
  66. protected $connFailureErrors = [];
  67. /** @var int */
  68. private static $GC_DELAY_SEC = 1;
  69. /** @var string */
  70. private static $OP_SET = 'set';
  71. /** @var string */
  72. private static $OP_ADD = 'add';
  73. /** @var string */
  74. private static $OP_TOUCH = 'touch';
  75. /** @var string */
  76. private static $OP_DELETE = 'delete';
  77. /**
  78. * Constructor. Parameters are:
  79. * - server: A server info structure in the format required by each
  80. * element in $wgDBServers.
  81. *
  82. * - servers: An array of server info structures describing a set of database servers
  83. * to distribute keys to. If this is specified, the "server" option will be
  84. * ignored. If string keys are used, then they will be used for consistent
  85. * hashing *instead* of the host name (from the server config). This is useful
  86. * when a cluster is replicated to another site (with different host names)
  87. * but each server has a corresponding replica in the other cluster.
  88. *
  89. * - purgePeriod: The average number of object cache writes in between
  90. * garbage collection operations, where expired entries
  91. * are removed from the database. Or in other words, the
  92. * reciprocal of the probability of purging on any given
  93. * write. If this is set to zero, purging will never be done.
  94. *
  95. * - purgeLimit: Maximum number of rows to purge at once.
  96. *
  97. * - tableName: The table name to use, default is "objectcache".
  98. *
  99. * - shards: The number of tables to use for data storage on each server.
  100. * If this is more than 1, table names will be formed in the style
  101. * objectcacheNNN where NNN is the shard index, between 0 and
  102. * shards-1. The number of digits will be the minimum number
  103. * required to hold the largest shard index. Data will be
  104. * distributed across all tables by key hash. This is for
  105. * MySQL bugs 61735 <https://bugs.mysql.com/bug.php?id=61735>
  106. * and 61736 <https://bugs.mysql.com/bug.php?id=61736>.
  107. *
  108. * - replicaOnly: Whether to only use replica DBs and avoid triggering
  109. * garbage collection logic of expired items. This only
  110. * makes sense if the primary DB is used and only if get()
  111. * calls will be used. This is used by ReplicatedBagOStuff.
  112. * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
  113. *
  114. * @param array $params
  115. */
  116. public function __construct( $params ) {
  117. parent::__construct( $params );
  118. $this->attrMap[self::ATTR_EMULATION] = self::QOS_EMULATION_SQL;
  119. $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_NONE;
  120. if ( isset( $params['servers'] ) ) {
  121. $this->serverInfos = [];
  122. $this->serverTags = [];
  123. $this->numServerShards = count( $params['servers'] );
  124. $index = 0;
  125. foreach ( $params['servers'] as $tag => $info ) {
  126. $this->serverInfos[$index] = $info;
  127. if ( is_string( $tag ) ) {
  128. $this->serverTags[$index] = $tag;
  129. } else {
  130. $this->serverTags[$index] = $info['host'] ?? "#$index";
  131. }
  132. ++$index;
  133. }
  134. } elseif ( isset( $params['server'] ) ) {
  135. $this->serverInfos = [ $params['server'] ];
  136. $this->numServerShards = count( $this->serverInfos );
  137. } else {
  138. // Default to using the main wiki's database servers
  139. $this->serverInfos = [];
  140. $this->numServerShards = 1;
  141. $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_BE;
  142. }
  143. if ( isset( $params['purgePeriod'] ) ) {
  144. $this->purgePeriod = intval( $params['purgePeriod'] );
  145. }
  146. if ( isset( $params['purgeLimit'] ) ) {
  147. $this->purgeLimit = intval( $params['purgeLimit'] );
  148. }
  149. if ( isset( $params['tableName'] ) ) {
  150. $this->tableName = $params['tableName'];
  151. }
  152. if ( isset( $params['shards'] ) ) {
  153. $this->numTableShards = intval( $params['shards'] );
  154. }
  155. // Backwards-compatibility for < 1.34
  156. $this->replicaOnly = $params['replicaOnly'] ?? ( $params['slaveOnly'] ?? false );
  157. }
  158. /**
  159. * Get a connection to the specified database
  160. *
  161. * @param int $shardIndex
  162. * @return IMaintainableDatabase
  163. * @throws MWException
  164. */
  165. private function getConnection( $shardIndex ) {
  166. if ( $shardIndex >= $this->numServerShards ) {
  167. throw new MWException( __METHOD__ . ": Invalid server index \"$shardIndex\"" );
  168. }
  169. # Don't keep timing out trying to connect for each call if the DB is down
  170. if (
  171. isset( $this->connFailureErrors[$shardIndex] ) &&
  172. ( $this->getCurrentTime() - $this->connFailureTimes[$shardIndex] ) < 60
  173. ) {
  174. throw $this->connFailureErrors[$shardIndex];
  175. }
  176. if ( $this->serverInfos ) {
  177. if ( !isset( $this->conns[$shardIndex] ) ) {
  178. // Use custom database defined by server connection info
  179. $info = $this->serverInfos[$shardIndex];
  180. $type = $info['type'] ?? 'mysql';
  181. $host = $info['host'] ?? '[unknown]';
  182. $this->logger->debug( __CLASS__ . ": connecting to $host" );
  183. $conn = Database::factory( $type, $info );
  184. $conn->clearFlag( DBO_TRX ); // auto-commit mode
  185. $this->conns[$shardIndex] = $conn;
  186. // Automatically create the objectcache table for sqlite as needed
  187. if ( $conn->getType() === 'sqlite' ) {
  188. $this->initSqliteDatabase( $conn );
  189. }
  190. }
  191. $conn = $this->conns[$shardIndex];
  192. } else {
  193. // Use the main LB database
  194. $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
  195. $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
  196. // If the RDBMS has row-level locking, use the autocommit connection to avoid
  197. // contention and deadlocks. Do not do this if it only has DB-level locking since
  198. // that would just cause deadlocks.
  199. $attribs = $lb->getServerAttributes( $lb->getWriterIndex() );
  200. $flags = $attribs[Database::ATTR_DB_LEVEL_LOCKING] ? 0 : $lb::CONN_TRX_AUTOCOMMIT;
  201. $conn = $lb->getMaintenanceConnectionRef( $index, [], false, $flags );
  202. }
  203. $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $conn ) );
  204. return $conn;
  205. }
  206. /**
  207. * Get the server index and table name for a given key
  208. * @param string $key
  209. * @return array Server index and table name
  210. */
  211. private function getTableByKey( $key ) {
  212. if ( $this->numTableShards > 1 ) {
  213. $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
  214. $tableIndex = $hash % $this->numTableShards;
  215. } else {
  216. $tableIndex = 0;
  217. }
  218. if ( $this->numServerShards > 1 ) {
  219. $sortedServers = $this->serverTags;
  220. ArrayUtils::consistentHashSort( $sortedServers, $key );
  221. reset( $sortedServers );
  222. $shardIndex = key( $sortedServers );
  223. } else {
  224. $shardIndex = 0;
  225. }
  226. return [ $shardIndex, $this->getTableNameByShard( $tableIndex ) ];
  227. }
  228. /**
  229. * Get the table name for a given shard index
  230. * @param int $index
  231. * @return string
  232. */
  233. private function getTableNameByShard( $index ) {
  234. if ( $this->numTableShards > 1 ) {
  235. $decimals = strlen( $this->numTableShards - 1 );
  236. return $this->tableName .
  237. sprintf( "%0{$decimals}d", $index );
  238. } else {
  239. return $this->tableName;
  240. }
  241. }
  242. protected function doGet( $key, $flags = 0, &$casToken = null ) {
  243. $casToken = null;
  244. $blobs = $this->fetchBlobMulti( [ $key ] );
  245. if ( array_key_exists( $key, $blobs ) ) {
  246. $blob = $blobs[$key];
  247. $value = $this->unserialize( $blob );
  248. $casToken = ( $value !== false ) ? $blob : null;
  249. return $value;
  250. }
  251. return false;
  252. }
  253. protected function doGetMulti( array $keys, $flags = 0 ) {
  254. $values = [];
  255. $blobs = $this->fetchBlobMulti( $keys );
  256. foreach ( $blobs as $key => $blob ) {
  257. $values[$key] = $this->unserialize( $blob );
  258. }
  259. return $values;
  260. }
  261. private function fetchBlobMulti( array $keys, $flags = 0 ) {
  262. $values = []; // array of (key => value)
  263. $keysByTable = [];
  264. foreach ( $keys as $key ) {
  265. list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
  266. $keysByTable[$shardIndex][$tableName][] = $key;
  267. }
  268. $dataRows = [];
  269. foreach ( $keysByTable as $shardIndex => $serverKeys ) {
  270. try {
  271. $db = $this->getConnection( $shardIndex );
  272. foreach ( $serverKeys as $tableName => $tableKeys ) {
  273. $res = $db->select( $tableName,
  274. [ 'keyname', 'value', 'exptime' ],
  275. [ 'keyname' => $tableKeys ],
  276. __METHOD__,
  277. // Approximate write-on-the-fly BagOStuff API via blocking.
  278. // This approximation fails if a ROLLBACK happens (which is rare).
  279. // We do not want to flush the TRX as that can break callers.
  280. $db->trxLevel() ? [ 'LOCK IN SHARE MODE' ] : []
  281. );
  282. if ( $res === false ) {
  283. continue;
  284. }
  285. foreach ( $res as $row ) {
  286. $row->shardIndex = $shardIndex;
  287. $row->tableName = $tableName;
  288. $dataRows[$row->keyname] = $row;
  289. }
  290. }
  291. } catch ( DBError $e ) {
  292. $this->handleReadError( $e, $shardIndex );
  293. }
  294. }
  295. foreach ( $keys as $key ) {
  296. if ( isset( $dataRows[$key] ) ) { // HIT?
  297. $row = $dataRows[$key];
  298. $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
  299. $db = null; // in case of connection failure
  300. try {
  301. $db = $this->getConnection( $row->shardIndex );
  302. if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
  303. $this->debug( "get: key has expired" );
  304. } else { // HIT
  305. $values[$key] = $db->decodeBlob( $row->value );
  306. }
  307. } catch ( DBQueryError $e ) {
  308. $this->handleWriteError( $e, $db, $row->shardIndex );
  309. }
  310. } else { // MISS
  311. $this->debug( 'get: no matching rows' );
  312. }
  313. }
  314. return $values;
  315. }
  316. protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
  317. return $this->modifyMulti( $data, $exptime, $flags, self::$OP_SET );
  318. }
  319. /**
  320. * @param mixed[]|null[] $data Map of (key => new value or null)
  321. * @param int $exptime UNIX timestamp, TTL in seconds, or 0 (no expiration)
  322. * @param int $flags Bitfield of BagOStuff::WRITE_* constants
  323. * @param string $op Cache operation
  324. * @return bool
  325. */
  326. private function modifyMulti( array $data, $exptime, $flags, $op ) {
  327. $keysByTable = [];
  328. foreach ( $data as $key => $value ) {
  329. list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
  330. $keysByTable[$shardIndex][$tableName][] = $key;
  331. }
  332. $exptime = $this->getExpirationAsTimestamp( $exptime );
  333. $result = true;
  334. /** @noinspection PhpUnusedLocalVariableInspection */
  335. $silenceScope = $this->silenceTransactionProfiler();
  336. foreach ( $keysByTable as $shardIndex => $serverKeys ) {
  337. $db = null; // in case of connection failure
  338. try {
  339. $db = $this->getConnection( $shardIndex );
  340. $this->occasionallyGarbageCollect( $db ); // expire old entries if any
  341. $dbExpiry = $exptime ? $db->timestamp( $exptime ) : $this->getMaxDateTime( $db );
  342. } catch ( DBError $e ) {
  343. $this->handleWriteError( $e, $db, $shardIndex );
  344. $result = false;
  345. continue;
  346. }
  347. foreach ( $serverKeys as $tableName => $tableKeys ) {
  348. try {
  349. $result = $this->updateTableKeys(
  350. $op,
  351. $db,
  352. $tableName,
  353. $tableKeys,
  354. $data,
  355. $dbExpiry
  356. ) && $result;
  357. } catch ( DBError $e ) {
  358. $this->handleWriteError( $e, $db, $shardIndex );
  359. $result = false;
  360. }
  361. }
  362. }
  363. if ( $this->fieldHasFlags( $flags, self::WRITE_SYNC ) ) {
  364. $result = $this->waitForReplication() && $result;
  365. }
  366. return $result;
  367. }
  368. /**
  369. * @param string $op
  370. * @param IDatabase $db
  371. * @param string $table
  372. * @param string[] $tableKeys Keys in $data to update
  373. * @param mixed[]|null[] $data Map of (key => new value or null)
  374. * @param string $dbExpiry DB-encoded expiry
  375. * @return bool
  376. * @throws DBError
  377. * @throws InvalidArgumentException
  378. */
  379. private function updateTableKeys( $op, $db, $table, $tableKeys, $data, $dbExpiry ) {
  380. $success = true;
  381. if ( $op === self::$OP_ADD ) {
  382. $rows = [];
  383. foreach ( $tableKeys as $key ) {
  384. $rows[] = [
  385. 'keyname' => $key,
  386. 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
  387. 'exptime' => $dbExpiry
  388. ];
  389. }
  390. $db->delete(
  391. $table,
  392. [
  393. 'keyname' => $tableKeys,
  394. 'exptime <= ' . $db->addQuotes( $db->timestamp() )
  395. ],
  396. __METHOD__
  397. );
  398. $db->insert( $table, $rows, __METHOD__, [ 'IGNORE' ] );
  399. $success = ( $db->affectedRows() == count( $rows ) );
  400. } elseif ( $op === self::$OP_SET ) {
  401. $rows = [];
  402. foreach ( $tableKeys as $key ) {
  403. $rows[] = [
  404. 'keyname' => $key,
  405. 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
  406. 'exptime' => $dbExpiry
  407. ];
  408. }
  409. $db->replace( $table, [ 'keyname' ], $rows, __METHOD__ );
  410. } elseif ( $op === self::$OP_DELETE ) {
  411. $db->delete( $table, [ 'keyname' => $tableKeys ], __METHOD__ );
  412. } elseif ( $op === self::$OP_TOUCH ) {
  413. $db->update(
  414. $table,
  415. [ 'exptime' => $dbExpiry ],
  416. [
  417. 'keyname' => $tableKeys,
  418. 'exptime > ' . $db->addQuotes( $db->timestamp() )
  419. ],
  420. __METHOD__
  421. );
  422. $success = ( $db->affectedRows() == count( $tableKeys ) );
  423. } else {
  424. throw new InvalidArgumentException( "Invalid operation '$op'" );
  425. }
  426. return $success;
  427. }
  428. protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
  429. return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self::$OP_SET );
  430. }
  431. protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
  432. return $this->modifyMulti( [ $key => $value ], $exptime, $flags, self::$OP_ADD );
  433. }
  434. protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
  435. list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
  436. $exptime = $this->getExpirationAsTimestamp( $exptime );
  437. /** @noinspection PhpUnusedLocalVariableInspection */
  438. $silenceScope = $this->silenceTransactionProfiler();
  439. $db = null; // in case of connection failure
  440. try {
  441. $db = $this->getConnection( $shardIndex );
  442. // (T26425) use a replace if the db supports it instead of
  443. // delete/insert to avoid clashes with conflicting keynames
  444. $db->update(
  445. $tableName,
  446. [
  447. 'keyname' => $key,
  448. 'value' => $db->encodeBlob( $this->serialize( $value ) ),
  449. 'exptime' => $exptime
  450. ? $db->timestamp( $exptime )
  451. : $this->getMaxDateTime( $db )
  452. ],
  453. [
  454. 'keyname' => $key,
  455. 'value' => $db->encodeBlob( $casToken ),
  456. 'exptime > ' . $db->addQuotes( $db->timestamp() )
  457. ],
  458. __METHOD__
  459. );
  460. } catch ( DBQueryError $e ) {
  461. $this->handleWriteError( $e, $db, $shardIndex );
  462. return false;
  463. }
  464. $success = (bool)$db->affectedRows();
  465. if ( $this->fieldHasFlags( $flags, self::WRITE_SYNC ) ) {
  466. $success = $this->waitForReplication() && $success;
  467. }
  468. return $success;
  469. }
  470. protected function doDeleteMulti( array $keys, $flags = 0 ) {
  471. return $this->modifyMulti(
  472. array_fill_keys( $keys, null ),
  473. 0,
  474. $flags,
  475. self::$OP_DELETE
  476. );
  477. }
  478. protected function doDelete( $key, $flags = 0 ) {
  479. return $this->modifyMulti( [ $key => null ], 0, $flags, self::$OP_DELETE );
  480. }
  481. public function incr( $key, $step = 1, $flags = 0 ) {
  482. list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
  483. $newCount = false;
  484. /** @noinspection PhpUnusedLocalVariableInspection */
  485. $silenceScope = $this->silenceTransactionProfiler();
  486. $db = null; // in case of connection failure
  487. try {
  488. $db = $this->getConnection( $shardIndex );
  489. $encTimestamp = $db->addQuotes( $db->timestamp() );
  490. $db->update(
  491. $tableName,
  492. [ 'value = value + ' . (int)$step ],
  493. [ 'keyname' => $key, "exptime > $encTimestamp" ],
  494. __METHOD__
  495. );
  496. if ( $db->affectedRows() > 0 ) {
  497. $newValue = $db->selectField(
  498. $tableName,
  499. 'value',
  500. [ 'keyname' => $key, "exptime > $encTimestamp" ],
  501. __METHOD__
  502. );
  503. if ( $this->isInteger( $newValue ) ) {
  504. $newCount = (int)$newValue;
  505. }
  506. }
  507. } catch ( DBError $e ) {
  508. $this->handleWriteError( $e, $db, $shardIndex );
  509. }
  510. return $newCount;
  511. }
  512. public function decr( $key, $value = 1, $flags = 0 ) {
  513. return $this->incr( $key, -$value, $flags );
  514. }
  515. public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
  516. return $this->modifyMulti(
  517. array_fill_keys( $keys, null ),
  518. $exptime,
  519. $flags,
  520. self::$OP_TOUCH
  521. );
  522. }
  523. protected function doChangeTTL( $key, $exptime, $flags ) {
  524. return $this->modifyMulti( [ $key => null ], $exptime, $flags, self::$OP_TOUCH );
  525. }
  526. /**
  527. * @param IDatabase $db
  528. * @param string $exptime
  529. * @return bool
  530. */
  531. private function isExpired( IDatabase $db, $exptime ) {
  532. return (
  533. $exptime != $this->getMaxDateTime( $db ) &&
  534. ConvertibleTimestamp::convert( TS_UNIX, $exptime ) < $this->getCurrentTime()
  535. );
  536. }
  537. /**
  538. * @param IDatabase $db
  539. * @return string
  540. */
  541. private function getMaxDateTime( $db ) {
  542. if ( (int)$this->getCurrentTime() > 0x7fffffff ) {
  543. return $db->timestamp( 1 << 62 );
  544. } else {
  545. return $db->timestamp( 0x7fffffff );
  546. }
  547. }
  548. /**
  549. * @param IDatabase $db
  550. * @throws DBError
  551. */
  552. private function occasionallyGarbageCollect( IDatabase $db ) {
  553. if (
  554. // Random purging is enabled
  555. $this->purgePeriod &&
  556. // Only purge on one in every $this->purgePeriod writes
  557. mt_rand( 0, $this->purgePeriod - 1 ) == 0 &&
  558. // Avoid repeating the delete within a few seconds
  559. ( $this->getCurrentTime() - $this->lastGarbageCollect ) > self::$GC_DELAY_SEC
  560. ) {
  561. $garbageCollector = function () use ( $db ) {
  562. $this->deleteServerObjectsExpiringBefore(
  563. $db, $this->getCurrentTime(),
  564. null,
  565. $this->purgeLimit
  566. );
  567. $this->lastGarbageCollect = time();
  568. };
  569. if ( $this->asyncHandler ) {
  570. $this->lastGarbageCollect = $this->getCurrentTime(); // avoid duplicate enqueues
  571. ( $this->asyncHandler )( $garbageCollector );
  572. } else {
  573. $garbageCollector();
  574. }
  575. }
  576. }
  577. public function expireAll() {
  578. $this->deleteObjectsExpiringBefore( $this->getCurrentTime() );
  579. }
  580. public function deleteObjectsExpiringBefore(
  581. $timestamp,
  582. callable $progress = null,
  583. $limit = INF
  584. ) {
  585. /** @noinspection PhpUnusedLocalVariableInspection */
  586. $silenceScope = $this->silenceTransactionProfiler();
  587. $shardIndexes = range( 0, $this->numServerShards - 1 );
  588. shuffle( $shardIndexes );
  589. $ok = true;
  590. $keysDeletedCount = 0;
  591. foreach ( $shardIndexes as $numServersDone => $shardIndex ) {
  592. $db = null; // in case of connection failure
  593. try {
  594. $db = $this->getConnection( $shardIndex );
  595. $this->deleteServerObjectsExpiringBefore(
  596. $db,
  597. $timestamp,
  598. $progress,
  599. $limit,
  600. $numServersDone,
  601. $keysDeletedCount
  602. );
  603. } catch ( DBError $e ) {
  604. $this->handleWriteError( $e, $db, $shardIndex );
  605. $ok = false;
  606. }
  607. }
  608. return $ok;
  609. }
  610. /**
  611. * @param IDatabase $db
  612. * @param string|int $timestamp
  613. * @param callable|null $progressCallback
  614. * @param int $limit
  615. * @param int $serversDoneCount
  616. * @param int &$keysDeletedCount
  617. * @throws DBError
  618. */
  619. private function deleteServerObjectsExpiringBefore(
  620. IDatabase $db,
  621. $timestamp,
  622. $progressCallback,
  623. $limit,
  624. $serversDoneCount = 0,
  625. &$keysDeletedCount = 0
  626. ) {
  627. $cutoffUnix = ConvertibleTimestamp::convert( TS_UNIX, $timestamp );
  628. $shardIndexes = range( 0, $this->numTableShards - 1 );
  629. shuffle( $shardIndexes );
  630. foreach ( $shardIndexes as $numShardsDone => $shardIndex ) {
  631. $continue = null; // last exptime
  632. $lag = null; // purge lag
  633. do {
  634. $res = $db->select(
  635. $this->getTableNameByShard( $shardIndex ),
  636. [ 'keyname', 'exptime' ],
  637. array_merge(
  638. [ 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ) ],
  639. $continue ? [ 'exptime >= ' . $db->addQuotes( $continue ) ] : []
  640. ),
  641. __METHOD__,
  642. [ 'LIMIT' => min( $limit, 100 ), 'ORDER BY' => 'exptime' ]
  643. );
  644. if ( $res->numRows() ) {
  645. $row = $res->current();
  646. if ( $lag === null ) {
  647. $rowExpUnix = ConvertibleTimestamp::convert( TS_UNIX, $row->exptime );
  648. $lag = max( $cutoffUnix - $rowExpUnix, 1 );
  649. }
  650. $keys = [];
  651. foreach ( $res as $row ) {
  652. $keys[] = $row->keyname;
  653. $continue = $row->exptime;
  654. }
  655. $db->delete(
  656. $this->getTableNameByShard( $shardIndex ),
  657. [
  658. 'exptime < ' . $db->addQuotes( $db->timestamp( $cutoffUnix ) ),
  659. 'keyname' => $keys
  660. ],
  661. __METHOD__
  662. );
  663. $keysDeletedCount += $db->affectedRows();
  664. }
  665. if ( is_callable( $progressCallback ) ) {
  666. if ( $lag ) {
  667. $continueUnix = ConvertibleTimestamp::convert( TS_UNIX, $continue );
  668. $remainingLag = $cutoffUnix - $continueUnix;
  669. $processedLag = max( $lag - $remainingLag, 0 );
  670. $doneRatio = ( $numShardsDone + $processedLag / $lag ) / $this->numTableShards;
  671. } else {
  672. $doneRatio = 1;
  673. }
  674. $overallRatio = ( $doneRatio / $this->numServerShards )
  675. + ( $serversDoneCount / $this->numServerShards );
  676. call_user_func( $progressCallback, $overallRatio * 100 );
  677. }
  678. } while ( $res->numRows() && $keysDeletedCount < $limit );
  679. }
  680. }
  681. /**
  682. * Delete content of shard tables in every server.
  683. * Return true if the operation is successful, false otherwise.
  684. * @return bool
  685. */
  686. public function deleteAll() {
  687. /** @noinspection PhpUnusedLocalVariableInspection */
  688. $silenceScope = $this->silenceTransactionProfiler();
  689. for ( $shardIndex = 0; $shardIndex < $this->numServerShards; $shardIndex++ ) {
  690. $db = null; // in case of connection failure
  691. try {
  692. $db = $this->getConnection( $shardIndex );
  693. for ( $i = 0; $i < $this->numTableShards; $i++ ) {
  694. $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
  695. }
  696. } catch ( DBError $e ) {
  697. $this->handleWriteError( $e, $db, $shardIndex );
  698. return false;
  699. }
  700. }
  701. return true;
  702. }
  703. public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
  704. // Avoid deadlocks and allow lock reentry if specified
  705. if ( isset( $this->locks[$key] ) ) {
  706. if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
  707. ++$this->locks[$key]['depth'];
  708. return true;
  709. } else {
  710. return false;
  711. }
  712. }
  713. list( $shardIndex ) = $this->getTableByKey( $key );
  714. $db = null; // in case of connection failure
  715. try {
  716. $db = $this->getConnection( $shardIndex );
  717. $ok = $db->lock( $key, __METHOD__, $timeout );
  718. if ( $ok ) {
  719. $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
  720. }
  721. $this->logger->warning(
  722. __METHOD__ . " failed due to timeout for {key}.",
  723. [ 'key' => $key, 'timeout' => $timeout ]
  724. );
  725. return $ok;
  726. } catch ( DBError $e ) {
  727. $this->handleWriteError( $e, $db, $shardIndex );
  728. $ok = false;
  729. }
  730. return $ok;
  731. }
  732. public function unlock( $key ) {
  733. if ( !isset( $this->locks[$key] ) ) {
  734. return false;
  735. }
  736. if ( --$this->locks[$key]['depth'] <= 0 ) {
  737. unset( $this->locks[$key] );
  738. list( $shardIndex ) = $this->getTableByKey( $key );
  739. $db = null; // in case of connection failure
  740. try {
  741. $db = $this->getConnection( $shardIndex );
  742. $ok = $db->unlock( $key, __METHOD__ );
  743. if ( !$ok ) {
  744. $this->logger->warning(
  745. __METHOD__ . ' failed to release lock for {key}.',
  746. [ 'key' => $key ]
  747. );
  748. }
  749. } catch ( DBError $e ) {
  750. $this->handleWriteError( $e, $db, $shardIndex );
  751. $ok = false;
  752. }
  753. return $ok;
  754. }
  755. return true;
  756. }
  757. /**
  758. * Serialize an object and, if possible, compress the representation.
  759. * On typical message and page data, this can provide a 3X decrease
  760. * in storage requirements.
  761. *
  762. * @param mixed $data
  763. * @return string|int
  764. */
  765. protected function serialize( $data ) {
  766. if ( is_int( $data ) ) {
  767. return $data;
  768. }
  769. $serial = serialize( $data );
  770. if ( function_exists( 'gzdeflate' ) ) {
  771. $serial = gzdeflate( $serial );
  772. }
  773. return $serial;
  774. }
  775. /**
  776. * Unserialize and, if necessary, decompress an object.
  777. * @param string $serial
  778. * @return mixed
  779. */
  780. protected function unserialize( $serial ) {
  781. if ( $this->isInteger( $serial ) ) {
  782. return (int)$serial;
  783. }
  784. if ( function_exists( 'gzinflate' ) ) {
  785. AtEase::suppressWarnings();
  786. $decomp = gzinflate( $serial );
  787. AtEase::restoreWarnings();
  788. if ( $decomp !== false ) {
  789. $serial = $decomp;
  790. }
  791. }
  792. return unserialize( $serial );
  793. }
  794. /**
  795. * Handle a DBError which occurred during a read operation.
  796. *
  797. * @param DBError $exception
  798. * @param int $shardIndex
  799. */
  800. private function handleReadError( DBError $exception, $shardIndex ) {
  801. if ( $exception instanceof DBConnectionError ) {
  802. $this->markServerDown( $exception, $shardIndex );
  803. }
  804. $this->setAndLogDBError( $exception );
  805. }
  806. /**
  807. * Handle a DBQueryError which occurred during a write operation.
  808. *
  809. * @param DBError $exception
  810. * @param IDatabase|null $db DB handle or null if connection failed
  811. * @param int $shardIndex
  812. * @throws Exception
  813. */
  814. private function handleWriteError( DBError $exception, $db, $shardIndex ) {
  815. if ( !( $db instanceof IDatabase ) ) {
  816. $this->markServerDown( $exception, $shardIndex );
  817. }
  818. $this->setAndLogDBError( $exception );
  819. }
  820. /**
  821. * @param DBError $exception
  822. */
  823. private function setAndLogDBError( DBError $exception ) {
  824. $this->logger->error( "DBError: {$exception->getMessage()}" );
  825. if ( $exception instanceof DBConnectionError ) {
  826. $this->setLastError( BagOStuff::ERR_UNREACHABLE );
  827. $this->logger->debug( __METHOD__ . ": ignoring connection error" );
  828. } else {
  829. $this->setLastError( BagOStuff::ERR_UNEXPECTED );
  830. $this->logger->debug( __METHOD__ . ": ignoring query error" );
  831. }
  832. }
  833. /**
  834. * Mark a server down due to a DBConnectionError exception
  835. *
  836. * @param DBError $exception
  837. * @param int $shardIndex
  838. */
  839. private function markServerDown( DBError $exception, $shardIndex ) {
  840. unset( $this->conns[$shardIndex] ); // bug T103435
  841. $now = $this->getCurrentTime();
  842. if ( isset( $this->connFailureTimes[$shardIndex] ) ) {
  843. if ( $now - $this->connFailureTimes[$shardIndex] >= 60 ) {
  844. unset( $this->connFailureTimes[$shardIndex] );
  845. unset( $this->connFailureErrors[$shardIndex] );
  846. } else {
  847. $this->logger->debug( __METHOD__ . ": Server #$shardIndex already down" );
  848. return;
  849. }
  850. }
  851. $this->logger->info( __METHOD__ . ": Server #$shardIndex down until " . ( $now + 60 ) );
  852. $this->connFailureTimes[$shardIndex] = $now;
  853. $this->connFailureErrors[$shardIndex] = $exception;
  854. }
  855. /**
  856. * @param IMaintainableDatabase $db
  857. * @throws DBError
  858. */
  859. private function initSqliteDatabase( IMaintainableDatabase $db ) {
  860. if ( $db->tableExists( 'objectcache' ) ) {
  861. return;
  862. }
  863. // Use one table for SQLite; sharding does not seem to have much benefit
  864. $db->query( "PRAGMA journal_mode=WAL" ); // this is permanent
  865. $db->startAtomic( __METHOD__ ); // atomic DDL
  866. try {
  867. $encTable = $db->tableName( 'objectcache' );
  868. $encExptimeIndex = $db->addIdentifierQuotes( $db->tablePrefix() . 'exptime' );
  869. $db->query(
  870. "CREATE TABLE $encTable (\n" .
  871. " keyname BLOB NOT NULL default '' PRIMARY KEY,\n" .
  872. " value BLOB,\n" .
  873. " exptime TEXT\n" .
  874. ")",
  875. __METHOD__
  876. );
  877. $db->query( "CREATE INDEX $encExptimeIndex ON $encTable (exptime)" );
  878. $db->endAtomic( __METHOD__ );
  879. } catch ( DBError $e ) {
  880. $db->rollback( __METHOD__ );
  881. throw $e;
  882. }
  883. }
  884. /**
  885. * Create the shard tables on all databases (e.g. via eval.php/shell.php)
  886. */
  887. public function createTables() {
  888. for ( $shardIndex = 0; $shardIndex < $this->numServerShards; $shardIndex++ ) {
  889. $db = $this->getConnection( $shardIndex );
  890. if ( in_array( $db->getType(), [ 'mysql', 'postgres' ], true ) ) {
  891. for ( $i = 0; $i < $this->numTableShards; $i++ ) {
  892. $encBaseTable = $db->tableName( 'objectcache' );
  893. $encShardTable = $db->tableName( $this->getTableNameByShard( $i ) );
  894. $db->query( "CREATE TABLE $encShardTable LIKE $encBaseTable" );
  895. }
  896. }
  897. }
  898. }
  899. /**
  900. * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
  901. */
  902. private function usesMainDB() {
  903. return !$this->serverInfos;
  904. }
  905. private function waitForReplication() {
  906. if ( !$this->usesMainDB() ) {
  907. // Custom DB server list; probably doesn't use replication
  908. return true;
  909. }
  910. $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
  911. if ( $lb->getServerCount() <= 1 ) {
  912. return true; // no replica DBs
  913. }
  914. // Main LB is used; wait for any replica DBs to catch up
  915. try {
  916. $masterPos = $lb->getMasterPos();
  917. if ( !$masterPos ) {
  918. return true; // not applicable
  919. }
  920. $loop = new WaitConditionLoop(
  921. function () use ( $lb, $masterPos ) {
  922. return $lb->waitForAll( $masterPos, 1 );
  923. },
  924. $this->syncTimeout,
  925. $this->busyCallbacks
  926. );
  927. return ( $loop->invoke() === $loop::CONDITION_REACHED );
  928. } catch ( DBError $e ) {
  929. $this->setAndLogDBError( $e );
  930. return false;
  931. }
  932. }
  933. /**
  934. * Silence the transaction profiler until the return value falls out of scope
  935. *
  936. * @return ScopedCallback|null
  937. */
  938. private function silenceTransactionProfiler() {
  939. if ( !$this->usesMainDB() ) {
  940. // Custom DB is configured which either has no TransactionProfiler injected,
  941. // or has one specific for cache use, which we shouldn't silence
  942. return null;
  943. }
  944. $trxProfiler = Profiler::instance()->getTransactionProfiler();
  945. $oldSilenced = $trxProfiler->setSilenced( true );
  946. return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
  947. $trxProfiler->setSilenced( $oldSilenced );
  948. } );
  949. }
  950. }