MemcLockManager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?php
  2. /**
  3. * Version of LockManager based on using memcached servers.
  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 LockManager
  22. */
  23. use Wikimedia\WaitConditionLoop;
  24. /**
  25. * Manage locks using memcached servers.
  26. *
  27. * Version of LockManager based on using memcached servers.
  28. * This is meant for multi-wiki systems that may share files.
  29. * All locks are non-blocking, which avoids deadlocks.
  30. *
  31. * All lock requests for a resource, identified by a hash string, will map to one
  32. * bucket. Each bucket maps to one or several peer servers, each running memcached.
  33. * A majority of peers must agree for a lock to be acquired.
  34. *
  35. * @ingroup LockManager
  36. * @since 1.20
  37. */
  38. class MemcLockManager extends QuorumLockManager {
  39. /** @var array Mapping of lock types to the type actually used */
  40. protected $lockTypeMap = [
  41. self::LOCK_SH => self::LOCK_SH,
  42. self::LOCK_UW => self::LOCK_SH,
  43. self::LOCK_EX => self::LOCK_EX
  44. ];
  45. /** @var MemcachedBagOStuff[] Map of (server name => MemcachedBagOStuff) */
  46. protected $cacheServers = [];
  47. /** @var MapCacheLRU Server status cache */
  48. protected $statusCache;
  49. /**
  50. * Construct a new instance from configuration.
  51. *
  52. * @param array $config Parameters include:
  53. * - lockServers : Associative array of server names to "<IP>:<port>" strings.
  54. * - srvsByBucket : Array of 1-16 consecutive integer keys, starting from 0,
  55. * each having an odd-numbered list of server names (peers) as values.
  56. * - memcConfig : Configuration array for MemcachedBagOStuff::construct() with an
  57. * additional 'class' parameter specifying which MemcachedBagOStuff
  58. * subclass to use. The server names will be injected. [optional]
  59. * @throws Exception
  60. */
  61. public function __construct( array $config ) {
  62. parent::__construct( $config );
  63. // Sanitize srvsByBucket config to prevent PHP errors
  64. $this->srvsByBucket = array_filter( $config['srvsByBucket'], 'is_array' );
  65. $this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive
  66. $memcConfig = $config['memcConfig'] ?? [];
  67. $memcConfig += [ 'class' => MemcachedPhpBagOStuff::class ]; // default
  68. $class = $memcConfig['class'];
  69. if ( !is_subclass_of( $class, MemcachedBagOStuff::class ) ) {
  70. throw new InvalidArgumentException( "$class is not of type MemcachedBagOStuff." );
  71. }
  72. foreach ( $config['lockServers'] as $name => $address ) {
  73. $params = [ 'servers' => [ $address ] ] + $memcConfig;
  74. $this->cacheServers[$name] = new $class( $params );
  75. }
  76. $this->statusCache = new MapCacheLRU( 100 );
  77. }
  78. protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
  79. $status = StatusValue::newGood();
  80. $memc = $this->getCache( $lockSrv );
  81. // List of affected paths
  82. $paths = array_merge( ...array_values( $pathsByType ) );
  83. $paths = array_unique( $paths );
  84. // List of affected lock record keys
  85. $keys = array_map( [ $this, 'recordKeyForPath' ], $paths );
  86. // Lock all of the active lock record keys...
  87. if ( !$this->acquireMutexes( $memc, $keys ) ) {
  88. foreach ( $paths as $path ) {
  89. $status->fatal( 'lockmanager-fail-acquirelock', $path );
  90. }
  91. return $status;
  92. }
  93. // Fetch all the existing lock records...
  94. $lockRecords = $memc->getMulti( $keys );
  95. $now = time();
  96. // Check if the requested locks conflict with existing ones...
  97. foreach ( $pathsByType as $type => $paths ) {
  98. foreach ( $paths as $path ) {
  99. $locksKey = $this->recordKeyForPath( $path );
  100. $locksHeld = isset( $lockRecords[$locksKey] )
  101. ? self::sanitizeLockArray( $lockRecords[$locksKey] )
  102. : self::newLockArray(); // init
  103. foreach ( $locksHeld[self::LOCK_EX] as $session => $expiry ) {
  104. if ( $expiry < $now ) { // stale?
  105. unset( $locksHeld[self::LOCK_EX][$session] );
  106. } elseif ( $session !== $this->session ) {
  107. $status->fatal( 'lockmanager-fail-acquirelock', $path );
  108. }
  109. }
  110. if ( $type === self::LOCK_EX ) {
  111. foreach ( $locksHeld[self::LOCK_SH] as $session => $expiry ) {
  112. if ( $expiry < $now ) { // stale?
  113. unset( $locksHeld[self::LOCK_SH][$session] );
  114. } elseif ( $session !== $this->session ) {
  115. $status->fatal( 'lockmanager-fail-acquirelock', $path );
  116. }
  117. }
  118. }
  119. if ( $status->isOK() ) {
  120. // Register the session in the lock record array
  121. $locksHeld[$type][$this->session] = $now + $this->lockTTL;
  122. // We will update this record if none of the other locks conflict
  123. $lockRecords[$locksKey] = $locksHeld;
  124. }
  125. }
  126. }
  127. // If there were no lock conflicts, update all the lock records...
  128. if ( $status->isOK() ) {
  129. foreach ( $paths as $path ) {
  130. $locksKey = $this->recordKeyForPath( $path );
  131. $locksHeld = $lockRecords[$locksKey];
  132. $ok = $memc->set( $locksKey, $locksHeld, self::MAX_LOCK_TTL );
  133. if ( !$ok ) {
  134. $status->fatal( 'lockmanager-fail-acquirelock', $path );
  135. } else {
  136. $this->logger->debug( __METHOD__ . ": acquired lock on key $locksKey.\n" );
  137. }
  138. }
  139. }
  140. // Unlock all of the active lock record keys...
  141. $this->releaseMutexes( $memc, $keys );
  142. return $status;
  143. }
  144. protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
  145. $status = StatusValue::newGood();
  146. $memc = $this->getCache( $lockSrv );
  147. // List of affected paths
  148. $paths = array_merge( ...array_values( $pathsByType ) );
  149. $paths = array_unique( $paths );
  150. // List of affected lock record keys
  151. $keys = array_map( [ $this, 'recordKeyForPath' ], $paths );
  152. // Lock all of the active lock record keys...
  153. if ( !$this->acquireMutexes( $memc, $keys ) ) {
  154. foreach ( $paths as $path ) {
  155. $status->fatal( 'lockmanager-fail-releaselock', $path );
  156. }
  157. return $status;
  158. }
  159. // Fetch all the existing lock records...
  160. $lockRecords = $memc->getMulti( $keys );
  161. // Remove the requested locks from all records...
  162. foreach ( $pathsByType as $type => $paths ) {
  163. foreach ( $paths as $path ) {
  164. $locksKey = $this->recordKeyForPath( $path ); // lock record
  165. if ( !isset( $lockRecords[$locksKey] ) ) {
  166. $status->warning( 'lockmanager-fail-releaselock', $path );
  167. continue; // nothing to do
  168. }
  169. $locksHeld = $this->sanitizeLockArray( $lockRecords[$locksKey] );
  170. if ( isset( $locksHeld[$type][$this->session] ) ) {
  171. unset( $locksHeld[$type][$this->session] ); // unregister this session
  172. $lockRecords[$locksKey] = $locksHeld;
  173. } else {
  174. $status->warning( 'lockmanager-fail-releaselock', $path );
  175. }
  176. }
  177. }
  178. // Persist the new lock record values...
  179. foreach ( $paths as $path ) {
  180. $locksKey = $this->recordKeyForPath( $path );
  181. if ( !isset( $lockRecords[$locksKey] ) ) {
  182. continue; // nothing to do
  183. }
  184. $locksHeld = $lockRecords[$locksKey];
  185. if ( $locksHeld === $this->newLockArray() ) {
  186. $ok = $memc->delete( $locksKey );
  187. } else {
  188. $ok = $memc->set( $locksKey, $locksHeld, self::MAX_LOCK_TTL );
  189. }
  190. if ( $ok ) {
  191. $this->logger->debug( __METHOD__ . ": released lock on key $locksKey.\n" );
  192. } else {
  193. $status->fatal( 'lockmanager-fail-releaselock', $path );
  194. }
  195. }
  196. // Unlock all of the active lock record keys...
  197. $this->releaseMutexes( $memc, $keys );
  198. return $status;
  199. }
  200. /**
  201. * @see QuorumLockManager::releaseAllLocks()
  202. * @return StatusValue
  203. */
  204. protected function releaseAllLocks() {
  205. return StatusValue::newGood(); // not supported
  206. }
  207. /**
  208. * @see QuorumLockManager::isServerUp()
  209. * @param string $lockSrv
  210. * @return bool
  211. */
  212. protected function isServerUp( $lockSrv ) {
  213. return (bool)$this->getCache( $lockSrv );
  214. }
  215. /**
  216. * Get the MemcachedBagOStuff object for a $lockSrv
  217. *
  218. * @param string $lockSrv Server name
  219. * @return MemcachedBagOStuff|null
  220. */
  221. protected function getCache( $lockSrv ) {
  222. if ( !isset( $this->cacheServers[$lockSrv] ) ) {
  223. throw new InvalidArgumentException( "Invalid cache server '$lockSrv'." );
  224. }
  225. $online = $this->statusCache->get( "online:$lockSrv", 30 );
  226. if ( $online === null ) {
  227. $online = $this->cacheServers[$lockSrv]->set( __CLASS__ . ':ping', 1, 1 );
  228. if ( !$online ) { // server down?
  229. $this->logger->warning( __METHOD__ . ": Could not contact $lockSrv." );
  230. }
  231. $this->statusCache->set( "online:$lockSrv", (int)$online );
  232. }
  233. return $online ? $this->cacheServers[$lockSrv] : null;
  234. }
  235. /**
  236. * @param string $path
  237. * @return string
  238. */
  239. protected function recordKeyForPath( $path ) {
  240. return implode( ':', [ __CLASS__, 'locks', $this->sha1Base36Absolute( $path ) ] );
  241. }
  242. /**
  243. * @return array An empty lock structure for a key
  244. */
  245. protected function newLockArray() {
  246. return [ self::LOCK_SH => [], self::LOCK_EX => [] ];
  247. }
  248. /**
  249. * @param array $a
  250. * @return array An empty lock structure for a key
  251. */
  252. protected function sanitizeLockArray( $a ) {
  253. if ( is_array( $a ) && isset( $a[self::LOCK_EX] ) && isset( $a[self::LOCK_SH] ) ) {
  254. return $a;
  255. }
  256. $this->logger->error( __METHOD__ . ": reset invalid lock array." );
  257. return $this->newLockArray();
  258. }
  259. /**
  260. * @param MemcachedBagOStuff $memc
  261. * @param array $keys List of keys to acquire
  262. * @return bool
  263. */
  264. protected function acquireMutexes( MemcachedBagOStuff $memc, array $keys ) {
  265. $lockedKeys = [];
  266. // Acquire the keys in lexicographical order, to avoid deadlock problems.
  267. // If P1 is waiting to acquire a key P2 has, P2 can't also be waiting for a key P1 has.
  268. sort( $keys );
  269. // Try to quickly loop to acquire the keys, but back off after a few rounds.
  270. // This reduces memcached spam, especially in the rare case where a server acquires
  271. // some lock keys and dies without releasing them. Lock keys expire after a few minutes.
  272. $loop = new WaitConditionLoop(
  273. function () use ( $memc, $keys, &$lockedKeys ) {
  274. foreach ( array_diff( $keys, $lockedKeys ) as $key ) {
  275. if ( $memc->add( "$key:mutex", 1, 180 ) ) { // lock record
  276. $lockedKeys[] = $key;
  277. }
  278. }
  279. return array_diff( $keys, $lockedKeys )
  280. ? WaitConditionLoop::CONDITION_CONTINUE
  281. : true;
  282. },
  283. 3.0 // timeout
  284. );
  285. $loop->invoke();
  286. if ( count( $lockedKeys ) != count( $keys ) ) {
  287. $this->releaseMutexes( $memc, $lockedKeys ); // failed; release what was locked
  288. return false;
  289. }
  290. return true;
  291. }
  292. /**
  293. * @param MemcachedBagOStuff $memc
  294. * @param array $keys List of acquired keys
  295. */
  296. protected function releaseMutexes( MemcachedBagOStuff $memc, array $keys ) {
  297. foreach ( $keys as $key ) {
  298. $memc->delete( "$key:mutex" );
  299. }
  300. }
  301. /**
  302. * Make sure remaining locks get cleared for sanity
  303. */
  304. function __destruct() {
  305. while ( count( $this->locksHeld ) ) {
  306. foreach ( $this->locksHeld as $path => $locks ) {
  307. $this->doUnlock( [ $path ], self::LOCK_EX );
  308. $this->doUnlock( [ $path ], self::LOCK_SH );
  309. }
  310. }
  311. }
  312. }