PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/filerepo/backend/lockmanager/DBLockManager.php

https://bitbucket.org/brunodefraine/mediawiki
PHP | 469 lines | 270 code | 29 blank | 170 comment | 42 complexity | f6486ed08bbf80a451ba520931306880 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
  1. <?php
  2. /**
  3. * Version of LockManager based on using DB table locks.
  4. * This is meant for multi-wiki systems that may share files.
  5. * All locks are blocking, so it might be useful to set a small
  6. * lock-wait timeout via server config to curtail deadlocks.
  7. *
  8. * All lock requests for a resource, identified by a hash string, will map
  9. * to one bucket. Each bucket maps to one or several peer DBs, each on their
  10. * own server, all having the filelocks.sql tables (with row-level locking).
  11. * A majority of peer DBs must agree for a lock to be acquired.
  12. *
  13. * Caching is used to avoid hitting servers that are down.
  14. *
  15. * @ingroup LockManager
  16. * @since 1.19
  17. */
  18. class DBLockManager extends LockManager {
  19. /** @var Array Map of DB names to server config */
  20. protected $dbServers; // (DB name => server config array)
  21. /** @var Array Map of bucket indexes to peer DB lists */
  22. protected $dbsByBucket; // (bucket index => (ldb1, ldb2, ...))
  23. /** @var BagOStuff */
  24. protected $statusCache;
  25. protected $lockExpiry; // integer number of seconds
  26. protected $safeDelay; // integer number of seconds
  27. protected $session = 0; // random integer
  28. /** @var Array Map Database connections (DB name => Database) */
  29. protected $conns = array();
  30. /**
  31. * Construct a new instance from configuration.
  32. *
  33. * $config paramaters include:
  34. * 'dbServers' : Associative array of DB names to server configuration.
  35. * Configuration is an associative array that includes:
  36. * 'host' - DB server name
  37. * 'dbname' - DB name
  38. * 'type' - DB type (mysql,postgres,...)
  39. * 'user' - DB user
  40. * 'password' - DB user password
  41. * 'tablePrefix' - DB table prefix
  42. * 'flags' - DB flags (see DatabaseBase)
  43. * 'dbsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
  44. * each having an odd-numbered list of DB names (peers) as values.
  45. * Any DB named 'localDBMaster' will automatically use the DB master
  46. * settings for this wiki (without the need for a dbServers entry).
  47. * 'lockExpiry' : Lock timeout (seconds) for dropped connections. [optional]
  48. * This tells the DB server how long to wait before assuming
  49. * connection failure and releasing all the locks for a session.
  50. *
  51. * @param Array $config
  52. */
  53. public function __construct( array $config ) {
  54. $this->dbServers = isset( $config['dbServers'] )
  55. ? $config['dbServers']
  56. : array(); // likely just using 'localDBMaster'
  57. // Sanitize dbsByBucket config to prevent PHP errors
  58. $this->dbsByBucket = array_filter( $config['dbsByBucket'], 'is_array' );
  59. $this->dbsByBucket = array_values( $this->dbsByBucket ); // consecutive
  60. if ( isset( $config['lockExpiry'] ) ) {
  61. $this->lockExpiry = $config['lockExpiry'];
  62. } else {
  63. $met = ini_get( 'max_execution_time' );
  64. $this->lockExpiry = $met ? $met : 60; // use some sane amount if 0
  65. }
  66. $this->safeDelay = ( $this->lockExpiry <= 0 )
  67. ? 60 // pick a safe-ish number to match DB timeout default
  68. : $this->lockExpiry; // cover worst case
  69. foreach ( $this->dbsByBucket as $bucket ) {
  70. if ( count( $bucket ) > 1 ) {
  71. // Tracks peers that couldn't be queried recently to avoid lengthy
  72. // connection timeouts. This is useless if each bucket has one peer.
  73. $this->statusCache = wfGetMainCache();
  74. break;
  75. }
  76. }
  77. $this->session = '';
  78. for ( $i = 0; $i < 5; $i++ ) {
  79. $this->session .= mt_rand( 0, 2147483647 );
  80. }
  81. $this->session = wfBaseConvert( sha1( $this->session ), 16, 36, 31 );
  82. }
  83. /**
  84. * @see LockManager::doLock()
  85. */
  86. protected function doLock( array $paths, $type ) {
  87. $status = Status::newGood();
  88. $pathsToLock = array();
  89. // Get locks that need to be acquired (buckets => locks)...
  90. foreach ( $paths as $path ) {
  91. if ( isset( $this->locksHeld[$path][$type] ) ) {
  92. ++$this->locksHeld[$path][$type];
  93. } elseif ( isset( $this->locksHeld[$path][self::LOCK_EX] ) ) {
  94. $this->locksHeld[$path][$type] = 1;
  95. } else {
  96. $bucket = $this->getBucketFromKey( $path );
  97. $pathsToLock[$bucket][] = $path;
  98. }
  99. }
  100. $lockedPaths = array(); // files locked in this attempt
  101. // Attempt to acquire these locks...
  102. foreach ( $pathsToLock as $bucket => $paths ) {
  103. // Try to acquire the locks for this bucket
  104. $res = $this->doLockingQueryAll( $bucket, $paths, $type );
  105. if ( $res === 'cantacquire' ) {
  106. // Resources already locked by another process.
  107. // Abort and unlock everything we just locked.
  108. foreach ( $paths as $path ) {
  109. $status->fatal( 'lockmanager-fail-acquirelock', $path );
  110. }
  111. $status->merge( $this->doUnlock( $lockedPaths, $type ) );
  112. return $status;
  113. } elseif ( $res !== true ) {
  114. // Couldn't contact any DBs for this bucket.
  115. // Abort and unlock everything we just locked.
  116. $status->fatal( 'lockmanager-fail-db-bucket', $bucket );
  117. $status->merge( $this->doUnlock( $lockedPaths, $type ) );
  118. return $status;
  119. }
  120. // Record these locks as active
  121. foreach ( $paths as $path ) {
  122. $this->locksHeld[$path][$type] = 1; // locked
  123. }
  124. // Keep track of what locks were made in this attempt
  125. $lockedPaths = array_merge( $lockedPaths, $paths );
  126. }
  127. return $status;
  128. }
  129. /**
  130. * @see LockManager::doUnlock()
  131. */
  132. protected function doUnlock( array $paths, $type ) {
  133. $status = Status::newGood();
  134. foreach ( $paths as $path ) {
  135. if ( !isset( $this->locksHeld[$path] ) ) {
  136. $status->warning( 'lockmanager-notlocked', $path );
  137. } elseif ( !isset( $this->locksHeld[$path][$type] ) ) {
  138. $status->warning( 'lockmanager-notlocked', $path );
  139. } else {
  140. --$this->locksHeld[$path][$type];
  141. if ( $this->locksHeld[$path][$type] <= 0 ) {
  142. unset( $this->locksHeld[$path][$type] );
  143. }
  144. if ( !count( $this->locksHeld[$path] ) ) {
  145. unset( $this->locksHeld[$path] ); // no SH or EX locks left for key
  146. }
  147. }
  148. }
  149. // Reference count the locks held and COMMIT when zero
  150. if ( !count( $this->locksHeld ) ) {
  151. $status->merge( $this->finishLockTransactions() );
  152. }
  153. return $status;
  154. }
  155. /**
  156. * Get a connection to a lock DB and acquire locks on $paths.
  157. * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
  158. *
  159. * @param $lockDb string
  160. * @param $paths Array
  161. * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
  162. * @return bool Resources able to be locked
  163. * @throws DBError
  164. */
  165. protected function doLockingQuery( $lockDb, array $paths, $type ) {
  166. if ( $type == self::LOCK_EX ) { // writer locks
  167. $db = $this->getConnection( $lockDb );
  168. if ( !$db ) {
  169. return false; // bad config
  170. }
  171. $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
  172. # Build up values for INSERT clause
  173. $data = array();
  174. foreach ( $keys as $key ) {
  175. $data[] = array( 'fle_key' => $key );
  176. }
  177. # Wait on any existing writers and block new ones if we get in
  178. $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
  179. }
  180. return true;
  181. }
  182. /**
  183. * Attempt to acquire locks with the peers for a bucket.
  184. * This should avoid throwing any exceptions.
  185. *
  186. * @param $bucket integer
  187. * @param $paths Array List of resource keys to lock
  188. * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
  189. * @return bool|string One of (true, 'cantacquire', 'dberrors')
  190. */
  191. protected function doLockingQueryAll( $bucket, array $paths, $type ) {
  192. $yesVotes = 0; // locks made on trustable DBs
  193. $votesLeft = count( $this->dbsByBucket[$bucket] ); // remaining DBs
  194. $quorum = floor( $votesLeft/2 + 1 ); // simple majority
  195. // Get votes for each DB, in order, until we have enough...
  196. foreach ( $this->dbsByBucket[$bucket] as $lockDb ) {
  197. // Check that DB is not *known* to be down
  198. if ( $this->cacheCheckFailures( $lockDb ) ) {
  199. try {
  200. // Attempt to acquire the lock on this DB
  201. if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
  202. return 'cantacquire'; // vetoed; resource locked
  203. }
  204. ++$yesVotes; // success for this peer
  205. if ( $yesVotes >= $quorum ) {
  206. return true; // lock obtained
  207. }
  208. } catch ( DBConnectionError $e ) {
  209. $this->cacheRecordFailure( $lockDb );
  210. } catch ( DBError $e ) {
  211. if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
  212. return 'cantacquire'; // vetoed; resource locked
  213. }
  214. }
  215. }
  216. --$votesLeft;
  217. $votesNeeded = $quorum - $yesVotes;
  218. if ( $votesNeeded > $votesLeft ) {
  219. // In "trust cache" mode we don't have to meet the quorum
  220. break; // short-circuit
  221. }
  222. }
  223. // At this point, we must not have meet the quorum
  224. return 'dberrors'; // not enough votes to ensure correctness
  225. }
  226. /**
  227. * Get (or reuse) a connection to a lock DB
  228. *
  229. * @param $lockDb string
  230. * @return Database
  231. * @throws DBError
  232. */
  233. protected function getConnection( $lockDb ) {
  234. if ( !isset( $this->conns[$lockDb] ) ) {
  235. $db = null;
  236. if ( $lockDb === 'localDBMaster' ) {
  237. $lb = wfGetLBFactory()->newMainLB();
  238. $db = $lb->getConnection( DB_MASTER );
  239. } elseif ( isset( $this->dbServers[$lockDb] ) ) {
  240. $config = $this->dbServers[$lockDb];
  241. $db = DatabaseBase::factory( $config['type'], $config );
  242. }
  243. if ( !$db ) {
  244. return null; // config error?
  245. }
  246. $this->conns[$lockDb] = $db;
  247. $this->conns[$lockDb]->clearFlag( DBO_TRX );
  248. # If the connection drops, try to avoid letting the DB rollback
  249. # and release the locks before the file operations are finished.
  250. # This won't handle the case of DB server restarts however.
  251. $options = array();
  252. if ( $this->lockExpiry > 0 ) {
  253. $options['connTimeout'] = $this->lockExpiry;
  254. }
  255. $this->conns[$lockDb]->setSessionOptions( $options );
  256. $this->initConnection( $lockDb, $this->conns[$lockDb] );
  257. }
  258. if ( !$this->conns[$lockDb]->trxLevel() ) {
  259. $this->conns[$lockDb]->begin(); // start transaction
  260. }
  261. return $this->conns[$lockDb];
  262. }
  263. /**
  264. * Do additional initialization for new lock DB connection
  265. *
  266. * @param $lockDb string
  267. * @param $db DatabaseBase
  268. * @return void
  269. * @throws DBError
  270. */
  271. protected function initConnection( $lockDb, DatabaseBase $db ) {}
  272. /**
  273. * Commit all changes to lock-active databases.
  274. * This should avoid throwing any exceptions.
  275. *
  276. * @return Status
  277. */
  278. protected function finishLockTransactions() {
  279. $status = Status::newGood();
  280. foreach ( $this->conns as $lockDb => $db ) {
  281. if ( $db->trxLevel() ) { // in transaction
  282. try {
  283. $db->rollback(); // finish transaction and kill any rows
  284. } catch ( DBError $e ) {
  285. $status->fatal( 'lockmanager-fail-db-release', $lockDb );
  286. }
  287. }
  288. }
  289. return $status;
  290. }
  291. /**
  292. * Check if the last DB error for $lockDb indicates
  293. * that a requested resource was locked by another process.
  294. * This should avoid throwing any exceptions.
  295. *
  296. * @param $lockDb string
  297. * @return bool
  298. */
  299. protected function lastErrorIndicatesLocked( $lockDb ) {
  300. if ( isset( $this->conns[$lockDb] ) ) { // sanity
  301. $db = $this->conns[$lockDb];
  302. return ( $db->wasDeadlock() || $db->wasLockTimeout() );
  303. }
  304. return false;
  305. }
  306. /**
  307. * Checks if the DB has not recently had connection/query errors.
  308. * This just avoids wasting time on doomed connection attempts.
  309. *
  310. * @param $lockDb string
  311. * @return bool
  312. */
  313. protected function cacheCheckFailures( $lockDb ) {
  314. if ( $this->statusCache && $this->safeDelay > 0 ) {
  315. $path = $this->getMissKey( $lockDb );
  316. $misses = $this->statusCache->get( $path );
  317. return !$misses;
  318. }
  319. return true;
  320. }
  321. /**
  322. * Log a lock request failure to the cache
  323. *
  324. * @param $lockDb string
  325. * @return bool Success
  326. */
  327. protected function cacheRecordFailure( $lockDb ) {
  328. if ( $this->statusCache && $this->safeDelay > 0 ) {
  329. $path = $this->getMissKey( $lockDb );
  330. $misses = $this->statusCache->get( $path );
  331. if ( $misses ) {
  332. return $this->statusCache->incr( $path );
  333. } else {
  334. return $this->statusCache->add( $path, 1, $this->safeDelay );
  335. }
  336. }
  337. return true;
  338. }
  339. /**
  340. * Get a cache key for recent query misses for a DB
  341. *
  342. * @param $lockDb string
  343. * @return string
  344. */
  345. protected function getMissKey( $lockDb ) {
  346. return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
  347. }
  348. /**
  349. * Get the bucket for resource path.
  350. * This should avoid throwing any exceptions.
  351. *
  352. * @param $path string
  353. * @return integer
  354. */
  355. protected function getBucketFromKey( $path ) {
  356. $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
  357. return intval( base_convert( $prefix, 16, 10 ) ) % count( $this->dbsByBucket );
  358. }
  359. /**
  360. * Make sure remaining locks get cleared for sanity
  361. */
  362. function __destruct() {
  363. foreach ( $this->conns as $lockDb => $db ) {
  364. if ( $db->trxLevel() ) { // in transaction
  365. try {
  366. $db->rollback(); // finish transaction and kill any rows
  367. } catch ( DBError $e ) {
  368. // oh well
  369. }
  370. }
  371. $db->close();
  372. }
  373. }
  374. }
  375. /**
  376. * MySQL version of DBLockManager that supports shared locks.
  377. * All locks are non-blocking, which avoids deadlocks.
  378. *
  379. * @ingroup LockManager
  380. */
  381. class MySqlLockManager extends DBLockManager {
  382. /** @var Array Mapping of lock types to the type actually used */
  383. protected $lockTypeMap = array(
  384. self::LOCK_SH => self::LOCK_SH,
  385. self::LOCK_UW => self::LOCK_SH,
  386. self::LOCK_EX => self::LOCK_EX
  387. );
  388. protected function initConnection( $lockDb, DatabaseBase $db ) {
  389. # Let this transaction see lock rows from other transactions
  390. $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
  391. }
  392. protected function doLockingQuery( $lockDb, array $paths, $type ) {
  393. $db = $this->getConnection( $lockDb );
  394. if ( !$db ) {
  395. return false;
  396. }
  397. $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
  398. # Build up values for INSERT clause
  399. $data = array();
  400. foreach ( $keys as $key ) {
  401. $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session );
  402. }
  403. # Block new writers...
  404. $db->insert( 'filelocks_shared', $data, __METHOD__, array( 'IGNORE' ) );
  405. # Actually do the locking queries...
  406. if ( $type == self::LOCK_SH ) { // reader locks
  407. # Bail if there are any existing writers...
  408. $blocked = $db->selectField( 'filelocks_exclusive', '1',
  409. array( 'fle_key' => $keys ),
  410. __METHOD__
  411. );
  412. # Prospective writers that haven't yet updated filelocks_exclusive
  413. # will recheck filelocks_shared after doing so and bail due to our entry.
  414. } else { // writer locks
  415. $encSession = $db->addQuotes( $this->session );
  416. # Bail if there are any existing writers...
  417. # The may detect readers, but the safe check for them is below.
  418. # Note: if two writers come at the same time, both bail :)
  419. $blocked = $db->selectField( 'filelocks_shared', '1',
  420. array( 'fls_key' => $keys, "fls_session != $encSession" ),
  421. __METHOD__
  422. );
  423. if ( !$blocked ) {
  424. # Build up values for INSERT clause
  425. $data = array();
  426. foreach ( $keys as $key ) {
  427. $data[] = array( 'fle_key' => $key );
  428. }
  429. # Block new readers/writers...
  430. $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
  431. # Bail if there are any existing readers...
  432. $blocked = $db->selectField( 'filelocks_shared', '1',
  433. array( 'fls_key' => $keys, "fls_session != $encSession" ),
  434. __METHOD__
  435. );
  436. }
  437. }
  438. return !$blocked;
  439. }
  440. }