-
Notifications
You must be signed in to change notification settings - Fork 167
/
RedLock.cs
720 lines (576 loc) · 19.9 KB
/
RedLock.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using RedLockNet.SERedis.Configuration;
using RedLockNet.SERedis.Internal;
using RedLockNet.SERedis.Util;
using StackExchange.Redis;
namespace RedLockNet.SERedis
{
public class RedLock : IRedLock
{
private readonly object lockObject = new object();
private readonly SemaphoreSlim extendUnlockSemaphore = new SemaphoreSlim(1, 1);
private readonly CancellationTokenSource unlockCancellationTokenSource = new CancellationTokenSource();
private readonly ICollection<RedisConnection> redisCaches;
private readonly ILogger<RedLock> logger;
private readonly int quorum;
private readonly int quorumRetryCount;
private readonly int quorumRetryDelayMs;
private const double ClockDriftFactor = 0.01;
private static readonly long ClockPrecisionPaddingTicks = TimeSpan.FromMilliseconds(2).Ticks;
private bool isDisposed;
private Timer lockKeepaliveTimer;
private static readonly string UnlockScript = EmbeddedResourceLoader.GetEmbeddedResource("RedLockNet.SERedis.Lua.Unlock.lua");
// Set the expiry for the given key if its value matches the supplied value.
// Returns 1 on success, 0 on failure setting expiry or key not existing, -1 if the key value didn't match
private static readonly string ExtendIfMatchingValueScript = EmbeddedResourceLoader.GetEmbeddedResource("RedLockNet.SERedis.Lua.Extend.lua");
public string Resource { get; }
public string LockId { get; }
public bool IsAcquired => Status == RedLockStatus.Acquired;
public RedLockStatus Status { get; private set; }
public RedLockInstanceSummary InstanceSummary { get; private set; }
public int ExtendCount { get; private set; }
private readonly TimeSpan expiryTime;
private readonly TimeSpan? waitTime;
private readonly TimeSpan? retryTime;
private CancellationToken cancellationToken;
private static readonly TimeSpan MinimumExpiryTime = TimeSpan.FromMilliseconds(10);
private static readonly TimeSpan MinimumRetryTime = TimeSpan.FromMilliseconds(10);
private const int DefaultQuorumRetryCount = 3;
private const int DefaultQuorumRetryDelayMs = 400;
private RedLock(
ILogger<RedLock> logger,
ICollection<RedisConnection> redisCaches,
string resource,
TimeSpan expiryTime,
TimeSpan? waitTime = null,
TimeSpan? retryTime = null,
RedLockRetryConfiguration retryConfiguration = null,
CancellationToken? cancellationToken = null)
{
this.logger = logger;
if (expiryTime < MinimumExpiryTime)
{
logger.LogWarning($"Expiry time {expiryTime.TotalMilliseconds}ms too low, setting to {MinimumExpiryTime.TotalMilliseconds}ms");
expiryTime = MinimumExpiryTime;
}
if (retryTime != null && retryTime.Value < MinimumRetryTime)
{
logger.LogWarning($"Retry time {retryTime.Value.TotalMilliseconds}ms too low, setting to {MinimumRetryTime.TotalMilliseconds}ms");
retryTime = MinimumRetryTime;
}
this.redisCaches = redisCaches;
quorum = redisCaches.Count / 2 + 1;
quorumRetryCount = retryConfiguration?.RetryCount ?? DefaultQuorumRetryCount;
quorumRetryDelayMs = retryConfiguration?.RetryDelayMs ?? DefaultQuorumRetryDelayMs;
Resource = resource;
LockId = Guid.NewGuid().ToString();
this.expiryTime = expiryTime;
this.waitTime = waitTime;
this.retryTime = retryTime;
this.cancellationToken = cancellationToken ?? CancellationToken.None;
}
internal static RedLock Create(
ILogger<RedLock> logger,
ICollection<RedisConnection> redisCaches,
string resource,
TimeSpan expiryTime,
TimeSpan? waitTime = null,
TimeSpan? retryTime = null,
RedLockRetryConfiguration retryConfiguration = null,
CancellationToken? cancellationToken = null)
{
var redisLock = new RedLock(
logger,
redisCaches,
resource,
expiryTime,
waitTime,
retryTime,
retryConfiguration,
cancellationToken);
redisLock.Start();
return redisLock;
}
internal static async Task<RedLock> CreateAsync(
ILogger<RedLock> logger,
ICollection<RedisConnection> redisCaches,
string resource,
TimeSpan expiryTime,
TimeSpan? waitTime = null,
TimeSpan? retryTime = null,
RedLockRetryConfiguration retryConfiguration = null,
CancellationToken? cancellationToken = null)
{
var redisLock = new RedLock(
logger,
redisCaches,
resource,
expiryTime,
waitTime,
retryTime,
retryConfiguration,
cancellationToken);
await redisLock.StartAsync().ConfigureAwait(false);
return redisLock;
}
private void Start()
{
if (waitTime.HasValue && retryTime.HasValue && waitTime.Value.TotalMilliseconds > 0 && retryTime.Value.TotalMilliseconds > 0)
{
var stopwatch = Stopwatch.StartNew();
// ReSharper disable PossibleInvalidOperationException
while (!IsAcquired && stopwatch.Elapsed <= waitTime.Value)
{
(Status, InstanceSummary) = Acquire();
if (!IsAcquired)
{
TaskUtils.Delay(retryTime.Value, cancellationToken).Wait(cancellationToken);
}
}
// ReSharper restore PossibleInvalidOperationException
}
else
{
(Status, InstanceSummary) = Acquire();
}
logger.LogInformation($"Lock status: {Status} ({InstanceSummary}), {Resource} ({LockId})");
if (IsAcquired)
{
StartAutoExtendTimer();
}
}
private async Task StartAsync()
{
if (waitTime.HasValue && retryTime.HasValue && waitTime.Value.TotalMilliseconds > 0 && retryTime.Value.TotalMilliseconds > 0)
{
var stopwatch = Stopwatch.StartNew();
// ReSharper disable PossibleInvalidOperationException
while (!IsAcquired && stopwatch.Elapsed <= waitTime.Value)
{
(Status, InstanceSummary) = await AcquireAsync().ConfigureAwait(false);
if (!IsAcquired)
{
await TaskUtils.Delay(retryTime.Value, cancellationToken).ConfigureAwait(false);
}
}
// ReSharper restore PossibleInvalidOperationException
}
else
{
(Status, InstanceSummary) = await AcquireAsync().ConfigureAwait(false);
}
logger.LogInformation($"Lock status: {Status} ({InstanceSummary}), {Resource} ({LockId})");
if (IsAcquired)
{
StartAutoExtendTimer();
}
}
private (RedLockStatus, RedLockInstanceSummary) Acquire()
{
var lockSummary = new RedLockInstanceSummary();
for (var i = 0; i < quorumRetryCount; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var iteration = i + 1;
logger.LogDebug($"Lock attempt {iteration}/{quorumRetryCount}: {Resource} ({LockId}), expiry: {expiryTime}");
var stopwatch = Stopwatch.StartNew();
lockSummary = Lock();
var validityTicks = GetRemainingValidityTicks(stopwatch);
logger.LogDebug($"Acquired locks for {Resource} ({LockId}) in {lockSummary.Acquired}/{redisCaches.Count} instances, quorum: {quorum}, validityTicks: {validityTicks}");
if (lockSummary.Acquired >= quorum && validityTicks > 0)
{
return (RedLockStatus.Acquired, lockSummary);
}
// we failed to get enough locks for a quorum, unlock everything and try again
Unlock();
// only sleep if we have more retries left
if (i < quorumRetryCount - 1)
{
var sleepMs = ThreadSafeRandom.Next(quorumRetryDelayMs);
logger.LogDebug($"Sleeping {sleepMs}ms");
TaskUtils.Delay(sleepMs, cancellationToken).Wait(cancellationToken);
}
}
var status = GetFailedRedLockStatus(lockSummary);
// give up
logger.LogDebug($"Could not acquire quorum after {quorumRetryCount} attempts, giving up: {Resource} ({LockId}). {lockSummary}.");
return (status, lockSummary);
}
private async Task<(RedLockStatus, RedLockInstanceSummary)> AcquireAsync()
{
var lockSummary = new RedLockInstanceSummary();
for (var i = 0; i < quorumRetryCount; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var iteration = i + 1;
logger.LogDebug($"Lock attempt {iteration}/{quorumRetryCount}: {Resource} ({LockId}), expiry: {expiryTime}");
var stopwatch = Stopwatch.StartNew();
lockSummary = await LockAsync().ConfigureAwait(false);
var validityTicks = GetRemainingValidityTicks(stopwatch);
logger.LogDebug($"Acquired locks for {Resource} ({LockId}) in {lockSummary.Acquired}/{redisCaches.Count} instances, quorum: {quorum}, validityTicks: {validityTicks}");
if (lockSummary.Acquired >= quorum && validityTicks > 0)
{
return (RedLockStatus.Acquired, lockSummary);
}
// we failed to get enough locks for a quorum, unlock everything and try again
await UnlockAsync().ConfigureAwait(false);
// only sleep if we have more retries left
if (i < quorumRetryCount - 1)
{
var sleepMs = ThreadSafeRandom.Next(quorumRetryDelayMs);
logger.LogDebug($"Sleeping {sleepMs}ms");
await TaskUtils.Delay(sleepMs, cancellationToken).ConfigureAwait(false);
}
}
var status = GetFailedRedLockStatus(lockSummary);
// give up
logger.LogDebug($"Could not acquire quorum after {quorumRetryCount} attempts, giving up: {Resource} ({LockId}). {lockSummary}.");
return (status, lockSummary);
}
private void StartAutoExtendTimer()
{
var interval = expiryTime.TotalMilliseconds / 2;
logger.LogDebug($"Starting auto extend timer with {interval}ms interval");
lockKeepaliveTimer = new Timer(
state => { ExtendLockLifetime(); },
null,
(int) interval,
(int) interval);
}
private void ExtendLockLifetime()
{
try
{
var gotSemaphore = extendUnlockSemaphore.Wait(0, unlockCancellationTokenSource.Token);
try
{
if (!gotSemaphore)
{
// another extend operation is still running, so skip this one
logger.LogWarning($"Lock renewal skipped due to another renewal still running: {Resource} ({LockId})");
return;
}
logger.LogTrace($"Lock renewal timer fired: {Resource} ({LockId})");
var stopwatch = Stopwatch.StartNew();
var extendSummary = Extend();
var validityTicks = GetRemainingValidityTicks(stopwatch);
if (extendSummary.Acquired >= quorum && validityTicks > 0)
{
Status = RedLockStatus.Acquired;
InstanceSummary = extendSummary;
ExtendCount++;
logger.LogDebug($"Extended lock, {Status} ({InstanceSummary}): {Resource} ({LockId})");
}
else
{
Status = GetFailedRedLockStatus(extendSummary);
InstanceSummary = extendSummary;
logger.LogWarning($"Failed to extend lock, {Status} ({InstanceSummary}): {Resource} ({LockId})");
}
}
catch (Exception exception)
{
// All we can do here is log the exception and swallow it.
var message = $"Lock renewal timer thread failed: {Resource} ({LockId})";
logger.LogError(null, exception, message);
}
finally
{
if (gotSemaphore)
{
extendUnlockSemaphore.Release();
}
}
}
catch (OperationCanceledException)
{
// unlock has been called, don't extend
logger.LogDebug($"Lock renewal cancelled: {Resource} ({LockId})");
}
}
private long GetRemainingValidityTicks(Stopwatch sw)
{
// Add 2 milliseconds to the drift to account for Redis expires precision,
// which is 1 milliescond, plus 1 millisecond min drift for small TTLs.
var driftTicks = (long) (expiryTime.Ticks * ClockDriftFactor) + ClockPrecisionPaddingTicks;
var validityTicks = expiryTime.Ticks - sw.Elapsed.Ticks - driftTicks;
return validityTicks;
}
private RedLockInstanceSummary Lock()
{
var lockResults = new ConcurrentBag<RedLockInstanceResult>();
Parallel.ForEach(redisCaches, cache =>
{
lockResults.Add(LockInstance(cache));
});
return PopulateRedLockResult(lockResults);
}
private async Task<RedLockInstanceSummary> LockAsync()
{
var lockTasks = redisCaches.Select(LockInstanceAsync);
var lockResults = await TaskUtils.WhenAll(lockTasks).ConfigureAwait(false);
return PopulateRedLockResult(lockResults);
}
private RedLockInstanceSummary Extend()
{
var extendResults = new ConcurrentBag<RedLockInstanceResult>();
Parallel.ForEach(redisCaches, cache =>
{
extendResults.Add(ExtendInstance(cache));
});
return PopulateRedLockResult(extendResults);
}
private void Unlock()
{
// ReSharper disable once MethodSupportsCancellation
extendUnlockSemaphore.Wait();
try
{
Parallel.ForEach(redisCaches, UnlockInstance);
}
finally
{
extendUnlockSemaphore.Release();
}
}
private async Task UnlockAsync()
{
// ReSharper disable once MethodSupportsCancellation
await extendUnlockSemaphore.WaitAsync().ConfigureAwait(false);
try
{
var unlockTasks = redisCaches.Select(UnlockInstanceAsync);
await TaskUtils.WhenAll(unlockTasks).ConfigureAwait(false);
}
finally
{
extendUnlockSemaphore.Release();
}
}
private RedLockInstanceResult LockInstance(RedisConnection cache)
{
var redisKey = GetRedisKey(cache.RedisKeyFormat, Resource);
var host = GetHost(cache.ConnectionMultiplexer);
RedLockInstanceResult result;
try
{
logger.LogTrace($"LockInstance enter {host}: {redisKey}, {LockId}, {expiryTime}");
var redisResult = cache.ConnectionMultiplexer
.GetDatabase(cache.RedisDatabase)
.StringSet(redisKey, LockId, expiryTime, When.NotExists, CommandFlags.DemandMaster);
result = redisResult ? RedLockInstanceResult.Success : RedLockInstanceResult.Conflicted;
}
catch (Exception ex)
{
logger.LogDebug($"Error locking lock instance {host}: {ex.Message}");
result = RedLockInstanceResult.Error;
}
logger.LogTrace($"LockInstance exit {host}: {redisKey}, {LockId}, {result}");
return result;
}
private async Task<RedLockInstanceResult> LockInstanceAsync(RedisConnection cache)
{
var redisKey = GetRedisKey(cache.RedisKeyFormat, Resource);
var host = GetHost(cache.ConnectionMultiplexer);
RedLockInstanceResult result;
try
{
logger.LogTrace($"LockInstanceAsync enter {host}: {redisKey}, {LockId}, {expiryTime}");
var redisResult = await cache.ConnectionMultiplexer
.GetDatabase(cache.RedisDatabase)
.StringSetAsync(redisKey, LockId, expiryTime, When.NotExists, CommandFlags.DemandMaster)
.ConfigureAwait(false);
result = redisResult ? RedLockInstanceResult.Success : RedLockInstanceResult.Conflicted;
}
catch (Exception ex)
{
logger.LogDebug($"Error locking lock instance {host}: {ex.Message}");
result = RedLockInstanceResult.Error;
}
logger.LogTrace($"LockInstanceAsync exit {host}: {redisKey}, {LockId}, {result}");
return result;
}
private RedLockInstanceResult ExtendInstance(RedisConnection cache)
{
var redisKey = GetRedisKey(cache.RedisKeyFormat, Resource);
var host = GetHost(cache.ConnectionMultiplexer);
RedLockInstanceResult result;
try
{
logger.LogTrace($"ExtendInstance enter {host}: {redisKey}, {LockId}, {expiryTime}");
// Returns 1 on success, 0 on failure setting expiry or key not existing, -1 if the key value didn't match
var extendResult = (long) cache.ConnectionMultiplexer
.GetDatabase(cache.RedisDatabase)
.ScriptEvaluate(ExtendIfMatchingValueScript, new RedisKey[] {redisKey}, new RedisValue[] {LockId, (long) expiryTime.TotalMilliseconds}, CommandFlags.DemandMaster);
result = extendResult == 1 ? RedLockInstanceResult.Success
: extendResult == -1 ? RedLockInstanceResult.Conflicted
: RedLockInstanceResult.Error;
}
catch (Exception ex)
{
logger.LogDebug($"Error extending lock instance {host}: {ex.Message}");
result = RedLockInstanceResult.Error;
}
logger.LogTrace($"ExtendInstance exit {host}: {redisKey}, {LockId}, {result}");
return result;
}
private void UnlockInstance(RedisConnection cache)
{
var redisKey = GetRedisKey(cache.RedisKeyFormat, Resource);
var host = GetHost(cache.ConnectionMultiplexer);
var result = false;
try
{
logger.LogTrace($"UnlockInstance enter {host}: {redisKey}, {LockId}");
result = (bool) cache.ConnectionMultiplexer
.GetDatabase(cache.RedisDatabase)
.ScriptEvaluate(UnlockScript, new RedisKey[] {redisKey}, new RedisValue[] {LockId}, CommandFlags.DemandMaster);
}
catch (Exception ex)
{
logger.LogDebug($"Error unlocking lock instance {host}: {ex.Message}");
}
logger.LogTrace($"UnlockInstance exit {host}: {redisKey}, {LockId}, {result}");
}
private async Task<bool> UnlockInstanceAsync(RedisConnection cache)
{
var redisKey = GetRedisKey(cache.RedisKeyFormat, Resource);
var host = GetHost(cache.ConnectionMultiplexer);
var result = false;
try
{
logger.LogTrace($"UnlockInstanceAsync enter {host}: {redisKey}, {LockId}");
result = (bool) await cache.ConnectionMultiplexer
.GetDatabase(cache.RedisDatabase)
.ScriptEvaluateAsync(UnlockScript, new RedisKey[] { redisKey }, new RedisValue[] { LockId }, CommandFlags.DemandMaster)
.ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogDebug($"Error unlocking lock instance {host}: {ex.Message}");
}
logger.LogTrace($"UnlockInstanceAsync exit {host}: {redisKey}, {LockId}, {result}");
return result;
}
private static string GetRedisKey(string redisKeyFormat, string resource)
{
return string.Format(redisKeyFormat, resource);
}
internal static string GetHost(IConnectionMultiplexer cache)
{
var result = new StringBuilder();
foreach (var endPoint in cache.GetEndPoints())
{
var server = cache.GetServer(endPoint);
result.Append(server.EndPoint.GetFriendlyName());
result.Append(" (");
result.Append(server.IsSlave ? "slave" : "master");
result.Append(server.IsConnected ? "" : ", disconnected");
result.Append("), ");
}
if (result.Length >= 2)
{
result.Remove(result.Length - 2, 2);
}
return result.ToString();
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
logger.LogDebug($"Disposing {Resource} ({LockId})");
if (isDisposed)
{
return;
}
if (disposing)
{
StopKeepAliveTimer();
}
unlockCancellationTokenSource.Cancel();
Unlock();
Status = RedLockStatus.Unlocked;
InstanceSummary = new RedLockInstanceSummary();
isDisposed = true;
}
public ValueTask DisposeAsync()
{
return DisposeAsync(true);
}
protected virtual async ValueTask DisposeAsync(bool disposing)
{
logger.LogDebug($"Disposing {Resource} ({LockId})");
if (isDisposed)
{
return;
}
if (disposing)
{
StopKeepAliveTimer();
}
unlockCancellationTokenSource.Cancel();
await UnlockAsync().ConfigureAwait(false);
Status = RedLockStatus.Unlocked;
InstanceSummary = new RedLockInstanceSummary();
isDisposed = true;
}
private RedLockStatus GetFailedRedLockStatus(RedLockInstanceSummary lockResult)
{
if (lockResult.Acquired >= quorum)
{
// if we got here with a quorum then validity must have expired
return RedLockStatus.Expired;
}
if (lockResult.Acquired + lockResult.Conflicted >= quorum)
{
// we had enough instances for a quorum, but some were locked with another LockId
return RedLockStatus.Conflicted;
}
return RedLockStatus.NoQuorum;
}
private static RedLockInstanceSummary PopulateRedLockResult(IEnumerable<RedLockInstanceResult> instanceResults)
{
var acquired = 0;
var conflicted = 0;
var error = 0;
foreach (var instanceResult in instanceResults)
{
switch (instanceResult)
{
case RedLockInstanceResult.Success:
acquired++;
break;
case RedLockInstanceResult.Conflicted:
conflicted++;
break;
case RedLockInstanceResult.Error:
error++;
break;
}
}
return new RedLockInstanceSummary(acquired, conflicted, error);
}
internal void StopKeepAliveTimer()
{
lock (lockObject)
{
if (lockKeepaliveTimer != null)
{
lockKeepaliveTimer.Change(Timeout.Infinite, Timeout.Infinite);
lockKeepaliveTimer.Dispose();
lockKeepaliveTimer = null;
}
}
}
}
}