MemcacheLockingProvider.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Jaakko Salo <jaakkos@gmail.com>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\Lock;
  27. use OCP\AppFramework\Utility\ITimeFactory;
  28. use OCP\IMemcache;
  29. use OCP\IMemcacheTTL;
  30. use OCP\Lock\LockedException;
  31. class MemcacheLockingProvider extends AbstractLockingProvider {
  32. /** @var array<string, array{time: int, ttl: int}> */
  33. private array $oldTTLs = [];
  34. public function __construct(
  35. private IMemcache $memcache,
  36. private ITimeFactory $timeFactory,
  37. int $ttl = 3600,
  38. ) {
  39. parent::__construct($ttl);
  40. }
  41. private function setTTL(string $path, int $ttl = null, mixed $compare = null): void {
  42. if (is_null($ttl)) {
  43. $ttl = $this->ttl;
  44. }
  45. if ($this->memcache instanceof IMemcacheTTL) {
  46. if ($compare !== null) {
  47. $this->memcache->compareSetTTL($path, $compare, $ttl);
  48. } else {
  49. $this->memcache->setTTL($path, $ttl);
  50. }
  51. }
  52. }
  53. private function getTTL(string $path): int {
  54. if ($this->memcache instanceof IMemcacheTTL) {
  55. $ttl = $this->memcache->getTTL($path);
  56. return $ttl === false ? -1 : $ttl;
  57. } else {
  58. return -1;
  59. }
  60. }
  61. public function isLocked(string $path, int $type): bool {
  62. $lockValue = $this->memcache->get($path);
  63. if ($type === self::LOCK_SHARED) {
  64. return is_int($lockValue) && $lockValue > 0;
  65. } elseif ($type === self::LOCK_EXCLUSIVE) {
  66. return $lockValue === 'exclusive';
  67. } else {
  68. return false;
  69. }
  70. }
  71. public function acquireLock(string $path, int $type, ?string $readablePath = null): void {
  72. if ($type === self::LOCK_SHARED) {
  73. // save the old TTL to for `restoreTTL`
  74. $this->oldTTLs[$path] = [
  75. "ttl" => $this->getTTL($path),
  76. "time" => $this->timeFactory->getTime()
  77. ];
  78. if (!$this->memcache->inc($path)) {
  79. throw new LockedException($path, null, $this->getExistingLockForException($path), $readablePath);
  80. }
  81. } else {
  82. // when getting exclusive locks, we know there are no old TTLs to restore
  83. $this->memcache->add($path, 0);
  84. // ttl is updated automatically when the `set` succeeds
  85. if (!$this->memcache->cas($path, 0, 'exclusive')) {
  86. throw new LockedException($path, null, $this->getExistingLockForException($path), $readablePath);
  87. }
  88. unset($this->oldTTLs[$path]);
  89. }
  90. $this->setTTL($path);
  91. $this->markAcquire($path, $type);
  92. }
  93. public function releaseLock(string $path, int $type): void {
  94. if ($type === self::LOCK_SHARED) {
  95. $ownSharedLockCount = $this->getOwnSharedLockCount($path);
  96. $newValue = 0;
  97. if ($ownSharedLockCount === 0) { // if we are not holding the lock, don't try to release it
  98. return;
  99. }
  100. if ($ownSharedLockCount === 1) {
  101. $removed = $this->memcache->cad($path, 1); // if we're the only one having a shared lock we can remove it in one go
  102. if (!$removed) { //someone else also has a shared lock, decrease only
  103. $newValue = $this->memcache->dec($path);
  104. }
  105. } else {
  106. // if we own more than one lock ourselves just decrease
  107. $newValue = $this->memcache->dec($path);
  108. }
  109. if ($newValue > 0) {
  110. $this->restoreTTL($path);
  111. } else {
  112. unset($this->oldTTLs[$path]);
  113. }
  114. // if we somehow release more locks then exists, reset the lock
  115. if ($newValue < 0) {
  116. $this->memcache->cad($path, $newValue);
  117. }
  118. } elseif ($type === self::LOCK_EXCLUSIVE) {
  119. $this->memcache->cad($path, 'exclusive');
  120. }
  121. $this->markRelease($path, $type);
  122. }
  123. public function changeLock(string $path, int $targetType): void {
  124. if ($targetType === self::LOCK_SHARED) {
  125. if (!$this->memcache->cas($path, 'exclusive', 1)) {
  126. throw new LockedException($path, null, $this->getExistingLockForException($path));
  127. }
  128. } elseif ($targetType === self::LOCK_EXCLUSIVE) {
  129. // we can only change a shared lock to an exclusive if there's only a single owner of the shared lock
  130. if (!$this->memcache->cas($path, 1, 'exclusive')) {
  131. $this->restoreTTL($path);
  132. throw new LockedException($path, null, $this->getExistingLockForException($path));
  133. }
  134. unset($this->oldTTLs[$path]);
  135. }
  136. $this->setTTL($path);
  137. $this->markChange($path, $targetType);
  138. }
  139. /**
  140. * With shared locks, each time the lock is acquired, the ttl for the path is reset.
  141. *
  142. * Due to this "ttl extension" when a shared lock isn't freed correctly for any reason
  143. * the lock won't expire until no shared locks are required for the path for 1h.
  144. * This can lead to a client repeatedly trying to upload a file, and failing forever
  145. * because the lock never gets the opportunity to expire.
  146. *
  147. * To help the lock expire in this case, we lower the TTL back to what it was before we
  148. * took the shared lock *only* if nobody else got a shared lock after we did.
  149. *
  150. * This doesn't handle all cases where multiple requests are acquiring shared locks
  151. * but it should handle some of the more common ones and not hurt things further
  152. */
  153. private function restoreTTL(string $path): void {
  154. if (isset($this->oldTTLs[$path])) {
  155. $saved = $this->oldTTLs[$path];
  156. $elapsed = $this->timeFactory->getTime() - $saved['time'];
  157. // old value to compare to when setting ttl in case someone else changes the lock in the middle of this function
  158. $value = $this->memcache->get($path);
  159. $currentTtl = $this->getTTL($path);
  160. // what the old ttl would be given the time elapsed since we acquired the lock
  161. // note that if this gets negative the key will be expired directly when we set the ttl
  162. $remainingOldTtl = $saved['ttl'] - $elapsed;
  163. // what the currently ttl would be if nobody else acquired a lock since we did (+1 to cover rounding errors)
  164. $expectedTtl = $this->ttl - $elapsed + 1;
  165. // check if another request has acquired a lock (and didn't release it yet)
  166. if ($currentTtl <= $expectedTtl) {
  167. $this->setTTL($path, $remainingOldTtl, $value);
  168. }
  169. }
  170. }
  171. private function getExistingLockForException(string $path): string {
  172. $existing = $this->memcache->get($path);
  173. if (!$existing) {
  174. return 'none';
  175. } elseif ($existing === 'exclusive') {
  176. return $existing;
  177. } else {
  178. return $existing . ' shared locks';
  179. }
  180. }
  181. }