PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/objectcache/SqlBagOStuff.php

https://github.com/daevid/MWFork
PHP | 424 lines | 286 code | 56 blank | 82 comment | 44 complexity | f88a451bdd5947098b0e5db7e43c83e6 MD5 | raw file
  1. <?php
  2. /**
  3. * Class to store objects in the database
  4. *
  5. * @ingroup Cache
  6. */
  7. class SqlBagOStuff extends BagOStuff {
  8. /**
  9. * @var LoadBalancer
  10. */
  11. var $lb;
  12. /**
  13. * @var DatabaseBase
  14. */
  15. var $db;
  16. var $serverInfo;
  17. var $lastExpireAll = 0;
  18. var $purgePeriod = 100;
  19. var $shards = 1;
  20. var $tableName = 'objectcache';
  21. /**
  22. * Constructor. Parameters are:
  23. * - server: A server info structure in the format required by each
  24. * element in $wgDBServers.
  25. *
  26. * - purgePeriod: The average number of object cache requests in between
  27. * garbage collection operations, where expired entries
  28. * are removed from the database. Or in other words, the
  29. * reciprocal of the probability of purging on any given
  30. * request. If this is set to zero, purging will never be
  31. * done.
  32. *
  33. * - tableName: The table name to use, default is "objectcache".
  34. *
  35. * - shards: The number of tables to use for data storage. If this is
  36. * more than 1, table names will be formed in the style
  37. * objectcacheNNN where NNN is the shard index, between 0 and
  38. * shards-1. The number of digits will be the minimum number
  39. * required to hold the largest shard index. Data will be
  40. * distributed across all tables by key hash. This is for
  41. * MySQL bugs 61735 and 61736.
  42. *
  43. * @param $params array
  44. */
  45. public function __construct( $params ) {
  46. if ( isset( $params['server'] ) ) {
  47. $this->serverInfo = $params['server'];
  48. $this->serverInfo['load'] = 1;
  49. }
  50. if ( isset( $params['purgePeriod'] ) ) {
  51. $this->purgePeriod = intval( $params['purgePeriod'] );
  52. }
  53. if ( isset( $params['tableName'] ) ) {
  54. $this->tableName = $params['tableName'];
  55. }
  56. if ( isset( $params['shards'] ) ) {
  57. $this->shards = intval( $params['shards'] );
  58. }
  59. }
  60. /**
  61. * @return DatabaseBase
  62. */
  63. protected function getDB() {
  64. if ( !isset( $this->db ) ) {
  65. # If server connection info was given, use that
  66. if ( $this->serverInfo ) {
  67. $this->lb = new LoadBalancer( array(
  68. 'servers' => array( $this->serverInfo ) ) );
  69. $this->db = $this->lb->getConnection( DB_MASTER );
  70. $this->db->clearFlag( DBO_TRX );
  71. } else {
  72. # We must keep a separate connection to MySQL in order to avoid deadlocks
  73. # However, SQLite has an opposite behaviour.
  74. # @todo Investigate behaviour for other databases
  75. if ( wfGetDB( DB_MASTER )->getType() == 'sqlite' ) {
  76. $this->db = wfGetDB( DB_MASTER );
  77. } else {
  78. $this->lb = wfGetLBFactory()->newMainLB();
  79. $this->db = $this->lb->getConnection( DB_MASTER );
  80. $this->db->clearFlag( DBO_TRX );
  81. }
  82. }
  83. }
  84. return $this->db;
  85. }
  86. /**
  87. * Get the table name for a given key
  88. */
  89. protected function getTableByKey( $key ) {
  90. if ( $this->shards > 1 ) {
  91. $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
  92. return $this->getTableByShard( $hash % $this->shards );
  93. } else {
  94. return $this->tableName;
  95. }
  96. }
  97. /**
  98. * Get the table name for a given shard index
  99. */
  100. protected function getTableByShard( $index ) {
  101. if ( $this->shards > 1 ) {
  102. $decimals = strlen( $this->shards - 1 );
  103. return $this->tableName .
  104. sprintf( "%0{$decimals}d", $index );
  105. } else {
  106. return $this->tableName;
  107. }
  108. }
  109. public function get( $key ) {
  110. # expire old entries if any
  111. $this->garbageCollect();
  112. $db = $this->getDB();
  113. $tableName = $this->getTableByKey( $key );
  114. $row = $db->selectRow( $tableName, array( 'value', 'exptime' ),
  115. array( 'keyname' => $key ), __METHOD__ );
  116. if ( !$row ) {
  117. $this->debug( 'get: no matching rows' );
  118. return false;
  119. }
  120. $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
  121. if ( $this->isExpired( $row->exptime ) ) {
  122. $this->debug( "get: key has expired, deleting" );
  123. try {
  124. $db->begin();
  125. # Put the expiry time in the WHERE condition to avoid deleting a
  126. # newly-inserted value
  127. $db->delete( $tableName,
  128. array(
  129. 'keyname' => $key,
  130. 'exptime' => $row->exptime
  131. ), __METHOD__ );
  132. $db->commit();
  133. } catch ( DBQueryError $e ) {
  134. $this->handleWriteError( $e );
  135. }
  136. return false;
  137. }
  138. return $this->unserialize( $db->decodeBlob( $row->value ) );
  139. }
  140. public function set( $key, $value, $exptime = 0 ) {
  141. $db = $this->getDB();
  142. $exptime = intval( $exptime );
  143. if ( $exptime < 0 ) {
  144. $exptime = 0;
  145. }
  146. if ( $exptime == 0 ) {
  147. $encExpiry = $this->getMaxDateTime();
  148. } else {
  149. if ( $exptime < 3.16e8 ) { # ~10 years
  150. $exptime += time();
  151. }
  152. $encExpiry = $db->timestamp( $exptime );
  153. }
  154. try {
  155. $db->begin();
  156. // (bug 24425) use a replace if the db supports it instead of
  157. // delete/insert to avoid clashes with conflicting keynames
  158. $db->replace(
  159. $this->getTableByKey( $key ),
  160. array( 'keyname' ),
  161. array(
  162. 'keyname' => $key,
  163. 'value' => $db->encodeBlob( $this->serialize( $value ) ),
  164. 'exptime' => $encExpiry
  165. ), __METHOD__ );
  166. $db->commit();
  167. } catch ( DBQueryError $e ) {
  168. $this->handleWriteError( $e );
  169. return false;
  170. }
  171. return true;
  172. }
  173. public function delete( $key, $time = 0 ) {
  174. $db = $this->getDB();
  175. try {
  176. $db->begin();
  177. $db->delete(
  178. $this->getTableByKey( $key ),
  179. array( 'keyname' => $key ),
  180. __METHOD__ );
  181. $db->commit();
  182. } catch ( DBQueryError $e ) {
  183. $this->handleWriteError( $e );
  184. return false;
  185. }
  186. return true;
  187. }
  188. public function incr( $key, $step = 1 ) {
  189. $db = $this->getDB();
  190. $tableName = $this->getTableByKey( $key );
  191. $step = intval( $step );
  192. try {
  193. $db->begin();
  194. $row = $db->selectRow(
  195. $tableName,
  196. array( 'value', 'exptime' ),
  197. array( 'keyname' => $key ),
  198. __METHOD__,
  199. array( 'FOR UPDATE' ) );
  200. if ( $row === false ) {
  201. // Missing
  202. $db->commit();
  203. return null;
  204. }
  205. $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__ );
  206. if ( $this->isExpired( $row->exptime ) ) {
  207. // Expired, do not reinsert
  208. $db->commit();
  209. return null;
  210. }
  211. $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
  212. $newValue = $oldValue + $step;
  213. $db->insert( $tableName,
  214. array(
  215. 'keyname' => $key,
  216. 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
  217. 'exptime' => $row->exptime
  218. ), __METHOD__, 'IGNORE' );
  219. if ( $db->affectedRows() == 0 ) {
  220. // Race condition. See bug 28611
  221. $newValue = null;
  222. }
  223. $db->commit();
  224. } catch ( DBQueryError $e ) {
  225. $this->handleWriteError( $e );
  226. return null;
  227. }
  228. return $newValue;
  229. }
  230. public function keys() {
  231. $db = $this->getDB();
  232. $result = array();
  233. for ( $i = 0; $i < $this->shards; $i++ ) {
  234. $res = $db->select( $this->getTableByShard( $i ),
  235. array( 'keyname' ), false, __METHOD__ );
  236. foreach ( $res as $row ) {
  237. $result[] = $row->keyname;
  238. }
  239. }
  240. return $result;
  241. }
  242. protected function isExpired( $exptime ) {
  243. return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX, $exptime ) < time();
  244. }
  245. protected function getMaxDateTime() {
  246. if ( time() > 0x7fffffff ) {
  247. return $this->getDB()->timestamp( 1 << 62 );
  248. } else {
  249. return $this->getDB()->timestamp( 0x7fffffff );
  250. }
  251. }
  252. protected function garbageCollect() {
  253. if ( !$this->purgePeriod ) {
  254. // Disabled
  255. return;
  256. }
  257. // Only purge on one in every $this->purgePeriod requests.
  258. if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
  259. return;
  260. }
  261. $now = time();
  262. // Avoid repeating the delete within a few seconds
  263. if ( $now > ( $this->lastExpireAll + 1 ) ) {
  264. $this->lastExpireAll = $now;
  265. $this->expireAll();
  266. }
  267. }
  268. public function expireAll() {
  269. $db = $this->getDB();
  270. $now = $db->timestamp();
  271. try {
  272. for ( $i = 0; $i < $this->shards; $i++ ) {
  273. $db->begin();
  274. $db->delete(
  275. $this->getTableByShard( $i ),
  276. array( 'exptime < ' . $db->addQuotes( $now ) ),
  277. __METHOD__ );
  278. $db->commit();
  279. }
  280. } catch ( DBQueryError $e ) {
  281. $this->handleWriteError( $e );
  282. }
  283. }
  284. public function deleteAll() {
  285. $db = $this->getDB();
  286. try {
  287. for ( $i = 0; $i < $this->shards; $i++ ) {
  288. $db->begin();
  289. $db->delete( $this->getTableByShard( $i ), '*', __METHOD__ );
  290. $db->commit();
  291. }
  292. } catch ( DBQueryError $e ) {
  293. $this->handleWriteError( $e );
  294. }
  295. }
  296. /**
  297. * Serialize an object and, if possible, compress the representation.
  298. * On typical message and page data, this can provide a 3X decrease
  299. * in storage requirements.
  300. *
  301. * @param $data mixed
  302. * @return string
  303. */
  304. protected function serialize( &$data ) {
  305. $serial = serialize( $data );
  306. if ( function_exists( 'gzdeflate' ) ) {
  307. return gzdeflate( $serial );
  308. } else {
  309. return $serial;
  310. }
  311. }
  312. /**
  313. * Unserialize and, if necessary, decompress an object.
  314. * @param $serial string
  315. * @return mixed
  316. */
  317. protected function unserialize( $serial ) {
  318. if ( function_exists( 'gzinflate' ) ) {
  319. wfSuppressWarnings();
  320. $decomp = gzinflate( $serial );
  321. wfRestoreWarnings();
  322. if ( false !== $decomp ) {
  323. $serial = $decomp;
  324. }
  325. }
  326. $ret = unserialize( $serial );
  327. return $ret;
  328. }
  329. /**
  330. * Handle a DBQueryError which occurred during a write operation.
  331. * Ignore errors which are due to a read-only database, rethrow others.
  332. */
  333. protected function handleWriteError( $exception ) {
  334. $db = $this->getDB();
  335. if ( !$db->wasReadOnlyError() ) {
  336. throw $exception;
  337. }
  338. try {
  339. $db->rollback();
  340. } catch ( DBQueryError $e ) {
  341. }
  342. wfDebug( __METHOD__ . ": ignoring query error\n" );
  343. $db->ignoreErrors( false );
  344. }
  345. /**
  346. * Create shard tables. For use from eval.php.
  347. */
  348. public function createTables() {
  349. $db = $this->getDB();
  350. if ( $db->getType() !== 'mysql'
  351. || version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
  352. {
  353. throw new MWException( __METHOD__ . ' is not supported on this DB server' );
  354. }
  355. for ( $i = 0; $i < $this->shards; $i++ ) {
  356. $db->begin();
  357. $db->query(
  358. 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
  359. ' LIKE ' . $db->tableName( 'objectcache' ),
  360. __METHOD__ );
  361. $db->commit();
  362. }
  363. }
  364. }
  365. /**
  366. * Backwards compatibility alias
  367. */
  368. class MediaWikiBagOStuff extends SqlBagOStuff { }