Skip to content

Commit 7d8741c

Browse files
authored
Merge pull request #37469 from nextcloud/lock-restore-ttl
restore shared lock ttl to previous value when releasing
2 parents 728dfa6 + ff62154 commit 7d8741c

File tree

8 files changed

+154
-7
lines changed

8 files changed

+154
-7
lines changed

lib/private/Lock/MemcacheLockingProvider.php

Lines changed: 76 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,21 +27,42 @@
2727
*/
2828
namespace OC\Lock;
2929

30+
use OCP\AppFramework\Utility\ITimeFactory;
3031
use OCP\IMemcache;
3132
use OCP\IMemcacheTTL;
3233
use OCP\Lock\LockedException;
3334

3435
class MemcacheLockingProvider extends AbstractLockingProvider {
36+
/** @var array<string, array{time: int, ttl: int}> */
37+
private array $oldTTLs = [];
38+
3539
public function __construct(
3640
private IMemcache $memcache,
41+
private ITimeFactory $timeFactory,
3742
int $ttl = 3600,
3843
) {
3944
parent::__construct($ttl);
4045
}
4146

42-
private function setTTL(string $path): void {
47+
private function setTTL(string $path, int $ttl = null, ?int $compare = null): void {
48+
if (is_null($ttl)) {
49+
$ttl = $this->ttl;
50+
}
51+
if ($this->memcache instanceof IMemcacheTTL) {
52+
if ($compare !== null) {
53+
$this->memcache->compareSetTTL($path, $compare, $ttl);
54+
} else {
55+
$this->memcache->setTTL($path, $ttl);
56+
}
57+
}
58+
}
59+
60+
private function getTTL(string $path): int {
4361
if ($this->memcache instanceof IMemcacheTTL) {
44-
$this->memcache->setTTL($path, $this->ttl);
62+
$ttl = $this->memcache->getTTL($path);
63+
return $ttl === false ? -1 : $ttl;
64+
} else {
65+
return -1;
4566
}
4667
}
4768

@@ -58,14 +79,22 @@ public function isLocked(string $path, int $type): bool {
5879

5980
public function acquireLock(string $path, int $type, ?string $readablePath = null): void {
6081
if ($type === self::LOCK_SHARED) {
82+
// save the old TTL to for `restoreTTL`
83+
$this->oldTTLs[$path] = [
84+
"ttl" => $this->getTTL($path),
85+
"time" => $this->timeFactory->getTime()
86+
];
6187
if (!$this->memcache->inc($path)) {
6288
throw new LockedException($path, null, $this->getExistingLockForException($path), $readablePath);
6389
}
6490
} else {
91+
// when getting exclusive locks, we know there are no old TTLs to restore
6592
$this->memcache->add($path, 0);
93+
// ttl is updated automatically when the `set` succeeds
6694
if (!$this->memcache->cas($path, 0, 'exclusive')) {
6795
throw new LockedException($path, null, $this->getExistingLockForException($path), $readablePath);
6896
}
97+
unset($this->oldTTLs[$path]);
6998
}
7099
$this->setTTL($path);
71100
$this->markAcquire($path, $type);
@@ -88,6 +117,12 @@ public function releaseLock(string $path, int $type): void {
88117
$newValue = $this->memcache->dec($path);
89118
}
90119

120+
if ($newValue > 0) {
121+
$this->restoreTTL($path);
122+
} else {
123+
unset($this->oldTTLs[$path]);
124+
}
125+
91126
// if we somehow release more locks then exists, reset the lock
92127
if ($newValue < 0) {
93128
$this->memcache->cad($path, $newValue);
@@ -106,13 +141,52 @@ public function changeLock(string $path, int $targetType): void {
106141
} elseif ($targetType === self::LOCK_EXCLUSIVE) {
107142
// we can only change a shared lock to an exclusive if there's only a single owner of the shared lock
108143
if (!$this->memcache->cas($path, 1, 'exclusive')) {
144+
$this->restoreTTL($path);
109145
throw new LockedException($path, null, $this->getExistingLockForException($path));
110146
}
147+
unset($this->oldTTLs[$path]);
111148
}
112149
$this->setTTL($path);
113150
$this->markChange($path, $targetType);
114151
}
115152

153+
/**
154+
* With shared locks, each time the lock is acquired, the ttl for the path is reset.
155+
*
156+
* Due to this "ttl extension" when a shared lock isn't freed correctly for any reason
157+
* the lock won't expire until no shared locks are required for the path for 1h.
158+
* This can lead to a client repeatedly trying to upload a file, and failing forever
159+
* because the lock never gets the opportunity to expire.
160+
*
161+
* To help the lock expire in this case, we lower the TTL back to what it was before we
162+
* took the shared lock *only* if nobody else got a shared lock after we did.
163+
*
164+
* This doesn't handle all cases where multiple requests are acquiring shared locks
165+
* but it should handle some of the more common ones and not hurt things further
166+
*/
167+
private function restoreTTL(string $path): void {
168+
if (isset($this->oldTTLs[$path])) {
169+
$saved = $this->oldTTLs[$path];
170+
$elapsed = $this->timeFactory->getTime() - $saved['time'];
171+
172+
// old value to compare to when setting ttl in case someone else changes the lock in the middle of this function
173+
$value = $this->memcache->get($path);
174+
175+
$currentTtl = $this->getTTL($path);
176+
177+
// what the old ttl would be given the time elapsed since we acquired the lock
178+
// note that if this gets negative the key will be expired directly when we set the ttl
179+
$remainingOldTtl = $saved['ttl'] - $elapsed;
180+
// what the currently ttl would be if nobody else acquired a lock since we did (+1 to cover rounding errors)
181+
$expectedTtl = $this->ttl - $elapsed + 1;
182+
183+
// check if another request has acquired a lock (and didn't release it yet)
184+
if ($currentTtl <= $expectedTtl) {
185+
$this->setTTL($path, $remainingOldTtl, $value);
186+
}
187+
}
188+
}
189+
116190
private function getExistingLockForException(string $path): string {
117191
$existing = $this->memcache->get($path);
118192
if (!$existing) {

lib/private/Memcache/LoggerWrapperCache.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,10 +167,18 @@ public function cad($key, $old) {
167167
}
168168

169169
/** @inheritDoc */
170-
public function setTTL($key, $ttl) {
170+
public function setTTL(string $key, int $ttl) {
171171
$this->wrappedCache->setTTL($key, $ttl);
172172
}
173173

174+
public function getTTL(string $key): int|false {
175+
return $this->wrappedCache->getTTL($key);
176+
}
177+
178+
public function compareSetTTL(string $key, mixed $value, int $ttl): bool {
179+
return $this->wrappedCache->compareSetTTL($key, $value, $ttl);
180+
}
181+
174182
public static function isAvailable(): bool {
175183
return true;
176184
}

lib/private/Memcache/ProfilerWrapperCache.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,10 +183,18 @@ public function cad($key, $old) {
183183
}
184184

185185
/** @inheritDoc */
186-
public function setTTL($key, $ttl) {
186+
public function setTTL(string $key, int $ttl) {
187187
$this->wrappedCache->setTTL($key, $ttl);
188188
}
189189

190+
public function getTTL(string $key): int|false {
191+
return $this->wrappedCache->getTTL($key);
192+
}
193+
194+
public function compareSetTTL(string $key, mixed $value, int $ttl): bool {
195+
return $this->wrappedCache->compareSetTTL($key, $value, $ttl);
196+
}
197+
190198
public function offsetExists($offset): bool {
191199
return $this->hasKey($offset);
192200
}

lib/private/Memcache/Redis.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ class Redis extends Cache implements IMemcacheTTL {
4646
'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',
4747
'cf0e94b2e9ffc7e04395cf88f7583fc309985910',
4848
],
49+
'caSetTtl' => [
50+
'if redis.call("get", KEYS[1]) == ARGV[1] then redis.call("expire", KEYS[1], ARGV[2]) return 1 else return 0 end',
51+
'fa4acbc946d23ef41d7d3910880b60e6e4972d72',
52+
],
4953
];
5054

5155
/**
@@ -181,6 +185,17 @@ public function setTTL($key, $ttl) {
181185
$this->getCache()->expire($this->getPrefix() . $key, $ttl);
182186
}
183187

188+
public function getTTL(string $key): int|false {
189+
$ttl = $this->getCache()->ttl($this->getPrefix() . $key);
190+
return $ttl > 0 ? (int)$ttl : false;
191+
}
192+
193+
public function compareSetTTL(string $key, mixed $value, int $ttl): bool {
194+
$value = self::encodeValue($value);
195+
196+
return $this->evalLua('caSetTtl', [$key], [$value, $ttl]) > 0;
197+
}
198+
184199
public static function isAvailable(): bool {
185200
return \OC::$server->getGetRedisFactory()->isAvailable();
186201
}

lib/private/Server.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@
173173
use OCA\Theming\Util;
174174
use OCP\Accounts\IAccountManager;
175175
use OCP\App\IAppManager;
176+
use OCP\AppFramework\Utility\ITimeFactory;
176177
use OCP\Authentication\LoginCredentials\IStore;
177178
use OCP\Authentication\Token\IProvider as OCPIProvider;
178179
use OCP\BackgroundJob\IJobList;
@@ -1079,7 +1080,8 @@ public function __construct($webRoot, \OC\Config $config) {
10791080
$memcacheFactory = $c->get(ICacheFactory::class);
10801081
$memcache = $memcacheFactory->createLocking('lock');
10811082
if (!($memcache instanceof \OC\Memcache\NullCache)) {
1082-
return new MemcacheLockingProvider($memcache, $ttl);
1083+
$timeFactory = $c->get(ITimeFactory::class);
1084+
return new MemcacheLockingProvider($memcache, $timeFactory, $ttl);
10831085
}
10841086
return new DBLockingProvider(
10851087
$c->get(IDBConnection::class),

lib/public/IMemcacheTTL.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,22 @@ interface IMemcacheTTL extends IMemcache {
3535
* @param int $ttl time to live in seconds
3636
* @since 8.2.2
3737
*/
38-
public function setTTL($key, $ttl);
38+
public function setTTL(string $key, int $ttl);
39+
40+
/**
41+
* Get the ttl for an existing value, in seconds till expiry
42+
*
43+
* @return int|false
44+
* @since 27
45+
*/
46+
public function getTTL(string $key): int|false;
47+
/**
48+
* Set the ttl for an existing value if the value matches
49+
*
50+
* @param string $key
51+
* @param mixed $value
52+
* @param int $ttl time to live in seconds
53+
* @since 27
54+
*/
55+
public function compareSetTTL(string $key, $value, int $ttl): bool;
3956
}

tests/lib/Lock/MemcacheLockingProviderTest.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
namespace Test\Lock;
2323

2424
use OC\Memcache\ArrayCache;
25+
use OCP\AppFramework\Utility\ITimeFactory;
2526

2627
class MemcacheLockingProviderTest extends LockingProvider {
2728
/**
@@ -34,7 +35,8 @@ class MemcacheLockingProviderTest extends LockingProvider {
3435
*/
3536
protected function getInstance() {
3637
$this->memcache = new ArrayCache();
37-
return new \OC\Lock\MemcacheLockingProvider($this->memcache);
38+
$timeProvider = \OC::$server->get(ITimeFactory::class);
39+
return new \OC\Lock\MemcacheLockingProvider($this->memcache, $timeProvider);
3840
}
3941

4042
protected function tearDown(): void {

tests/lib/Memcache/RedisTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,18 @@
99

1010
namespace Test\Memcache;
1111

12+
use OC\Memcache\Redis;
13+
1214
/**
1315
* @group Memcache
1416
* @group Redis
1517
*/
1618
class RedisTest extends Cache {
19+
/**
20+
* @var Redis cache;
21+
*/
22+
protected $instance;
23+
1724
public static function setUpBeforeClass(): void {
1825
parent::setUpBeforeClass();
1926

@@ -62,4 +69,18 @@ public function testScriptHashes() {
6269
$this->assertEquals(sha1($script[0]), $script[1]);
6370
}
6471
}
72+
73+
public function testCasTtlNotChanged() {
74+
$this->instance->set('foo', 'bar', 50);
75+
$this->assertTrue($this->instance->compareSetTTL('foo', 'bar', 100));
76+
// allow for 1s of inaccuracy due to time moving forward
77+
$this->assertLessThan(1, 100 - $this->instance->getTTL('foo'));
78+
}
79+
80+
public function testCasTtlChanged() {
81+
$this->instance->set('foo', 'bar1', 50);
82+
$this->assertFalse($this->instance->compareSetTTL('foo', 'bar', 100));
83+
// allow for 1s of inaccuracy due to time moving forward
84+
$this->assertLessThan(1, 50 - $this->instance->getTTL('foo'));
85+
}
6586
}

0 commit comments

Comments
 (0)