-
Notifications
You must be signed in to change notification settings - Fork 289
/
AppLeaseManager.cs
557 lines (478 loc) · 19.7 KB
/
AppLeaseManager.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
// ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace DurableTask.AzureStorage.Partitioning
{
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using DurableTask.AzureStorage.Storage;
using Newtonsoft.Json;
/// <summary>
/// Class responsible for starting and stopping the partition manager. Also implements the app lease feature to ensure a single app's partition manager is started at a time.
/// </summary>
sealed class AppLeaseManager
{
readonly AzureStorageClient azureStorageClient;
readonly IPartitionManager partitionManager;
readonly AzureStorageOrchestrationServiceSettings settings;
readonly string appLeaseContainerName;
readonly string appLeaseInfoBlobName;
readonly AppLeaseOptions options;
readonly string storageAccountName;
readonly string taskHub;
readonly string workerName;
readonly string appName;
readonly bool appLeaseIsEnabled;
readonly BlobContainer appLeaseContainer;
readonly Blob appLeaseInfoBlob;
readonly string appLeaseId;
readonly AsyncManualResetEvent shutdownCompletedEvent;
bool isLeaseOwner;
int appLeaseIsStarted;
Task renewTask;
CancellationTokenSource starterTokenSource;
CancellationTokenSource leaseRenewerCancellationTokenSource;
public AppLeaseManager(
AzureStorageClient azureStorageClient,
IPartitionManager partitionManager,
string appLeaseContainerName,
string appLeaseInfoBlobName,
AppLeaseOptions options)
{
this.azureStorageClient = azureStorageClient;
this.partitionManager = partitionManager;
this.appLeaseContainerName = appLeaseContainerName;
this.appLeaseInfoBlobName = appLeaseInfoBlobName;
this.options = options;
this.storageAccountName = this.azureStorageClient.BlobAccountName;
this.settings = this.azureStorageClient.Settings;
this.taskHub = settings.TaskHubName;
this.workerName = settings.WorkerId;
this.appName = settings.AppName;
this.appLeaseIsEnabled = this.settings.UseAppLease;
this.appLeaseContainer = this.azureStorageClient.GetBlobContainerReference(this.appLeaseContainerName);
this.appLeaseInfoBlob = this.appLeaseContainer.GetBlobReference(this.appLeaseInfoBlobName);
var appNameHashInBytes = BitConverter.GetBytes(Fnv1aHashHelper.ComputeHash(this.appName));
Array.Resize(ref appNameHashInBytes, 16);
this.appLeaseId = new Guid(appNameHashInBytes).ToString();
this.isLeaseOwner = false;
this.shutdownCompletedEvent = new AsyncManualResetEvent();
}
public async Task StartAsync()
{
if (!this.appLeaseIsEnabled)
{
this.starterTokenSource = new CancellationTokenSource();
await Task.Factory.StartNew(() => this.PartitionManagerStarter(this.starterTokenSource.Token));
}
else
{
await RestartAppLeaseStarterTask();
}
}
async Task PartitionManagerStarter(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
await this.partitionManager.StartAsync();
break;
}
catch (Exception e)
{
this.settings.Logger.PartitionManagerError(
this.storageAccountName,
this.settings.TaskHubName,
this.workerName,
this.appLeaseContainerName,
$"Error in PartitionManagerStarter task. Exception: {e}");
}
}
}
async Task RestartAppLeaseStarterTask()
{
if (this.starterTokenSource != null)
{
this.starterTokenSource.Cancel();
this.starterTokenSource.Dispose();
}
this.starterTokenSource = new CancellationTokenSource();
await Task.Factory.StartNew(() => this.AppLeaseManagerStarter(this.starterTokenSource.Token));
}
async Task AppLeaseManagerStarter(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
while (!await this.TryAquireAppLeaseAsync())
{
await Task.Delay(this.settings.AppLeaseOptions.AcquireInterval, cancellationToken);
}
await this.StartAppLeaseAsync();
await this.shutdownCompletedEvent.WaitAsync(Timeout.InfiniteTimeSpan, cancellationToken);
}
catch (OperationCanceledException)
{
// Catch OperationCanceledException to avoid logging an error if the Task.Delay was cancelled.
}
catch (Exception e)
{
this.settings.Logger.PartitionManagerError(
this.storageAccountName,
this.settings.TaskHubName,
this.workerName,
this.appLeaseContainerName,
$"Error in AppLeaseStarter task. Exception: {e}");
}
}
}
public async Task StopAsync()
{
if (this.appLeaseIsEnabled)
{
await this.StopAppLeaseAsync();
}
else
{
await this.partitionManager.StopAsync();
}
this.starterTokenSource.Cancel();
this.starterTokenSource.Dispose();
}
public async Task ForceChangeAppLeaseAsync()
{
if (!this.appLeaseIsEnabled)
{
throw new InvalidOperationException("Cannot force change app lease. UseAppLease is not enabled.");
}
if (!this.isLeaseOwner)
{
await this.UpdateDesiredSwapAppIdToCurrentApp();
await this.RestartAppLeaseStarterTask();
}
}
public async Task<bool> CreateContainerIfNotExistsAsync()
{
bool result = await appLeaseContainer.CreateIfNotExistsAsync();
await this.CreateAppLeaseInfoIfNotExistsAsync();
return result;
}
public async Task DeleteContainerAsync()
{
try
{
if (this.isLeaseOwner)
{
await this.appLeaseContainer.DeleteIfExistsAsync(appLeaseId);
}
else
{
await this.appLeaseContainer.DeleteIfExistsAsync();
}
}
catch (DurableTaskStorageException)
{
// If we cannot delete the existing app lease due to another app having a lease, just ignore it.
}
}
async Task CreateAppLeaseInfoIfNotExistsAsync()
{
try
{
await this.appLeaseInfoBlob.UploadTextAsync("{}", ifDoesntExist: true);
}
catch (DurableTaskStorageException)
{
// eat any storage exception related to conflict
// this means the blob already exist
}
}
async Task StartAppLeaseAsync()
{
if (Interlocked.CompareExchange(ref this.appLeaseIsStarted, 1, 0) != 0)
{
throw new InvalidOperationException("AppLeaseManager has already started");
}
this.leaseRenewerCancellationTokenSource = new CancellationTokenSource();
await this.partitionManager.StartAsync();
this.shutdownCompletedEvent.Reset();
this.renewTask = await Task.Factory.StartNew(() => this.LeaseRenewer(leaseRenewerCancellationTokenSource.Token));
}
async Task StopAppLeaseAsync()
{
if (Interlocked.CompareExchange(ref this.appLeaseIsStarted, 0, 1) != 1)
{
//idempotent
return;
}
await this.partitionManager.StopAsync();
if (this.renewTask != null)
{
this.leaseRenewerCancellationTokenSource.Cancel();
await this.renewTask;
}
this.isLeaseOwner = false;
this.shutdownCompletedEvent.Set();
this.leaseRenewerCancellationTokenSource?.Dispose();
}
async Task<bool> TryAquireAppLeaseAsync()
{
AppLeaseInfo appLeaseInfo = await this.GetAppLeaseInfoAsync();
bool leaseAcquired;
if (appLeaseInfo.DesiredSwapId == this.appLeaseId)
{
leaseAcquired = await this.ChangeLeaseAsync(appLeaseInfo.OwnerId);
}
else
{
leaseAcquired = await this.TryAquireLeaseAsync();
}
this.isLeaseOwner = leaseAcquired;
return leaseAcquired;
}
async Task<bool> ChangeLeaseAsync(string currentLeaseId)
{
this.settings.Logger.PartitionManagerInfo(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName,
$"Attempting to change lease from current owner {currentLeaseId} to {this.appLeaseId}.");
bool leaseAcquired;
try
{
this.settings.Logger.LeaseAcquisitionStarted(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName);
await appLeaseContainer.ChangeLeaseAsync(this.appLeaseId, currentLeaseId);
var appLeaseInfo = new AppLeaseInfo()
{
OwnerId = this.appLeaseId,
};
await this.UpdateAppLeaseInfoBlob(appLeaseInfo);
leaseAcquired = true;
this.settings.Logger.LeaseAcquisitionSucceeded(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName);
// When changing the lease over to another app, the paritions will still be listened to on the first app until the AppLeaseManager
// renew task fails to renew the lease. To avoid potential split brain we must delay before the new lease holder can start
// listening to the partitions.
if (this.settings.UseLegacyPartitionManagement == true)
{
await Task.Delay(this.settings.AppLeaseOptions.RenewInterval);
}
}
catch (DurableTaskStorageException e)
{
leaseAcquired = false;
this.settings.Logger.PartitionManagerWarning(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName,
$"Failed to change app lease from currentLeaseId {currentLeaseId} to {this.appLeaseId}. Exception: {e.Message}");
}
return leaseAcquired;
}
async Task<bool> TryAquireLeaseAsync()
{
bool leaseAcquired;
try
{
this.settings.Logger.LeaseAcquisitionStarted(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName);
await appLeaseContainer.AcquireLeaseAsync(this.options.LeaseInterval, this.appLeaseId);
await this.UpdateOwnerAppIdToCurrentApp();
leaseAcquired = true;
this.settings.Logger.LeaseAcquisitionSucceeded(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName);
}
catch (DurableTaskStorageException e)
{
leaseAcquired = false;
this.settings.Logger.LeaseAcquisitionFailed(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName);
this.settings.Logger.PartitionManagerWarning(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName,
$"Failed to acquire app lease with appLeaseId {this.appLeaseId}. Another app likely has the lease on this container. Exception: {e.Message}");
}
return leaseAcquired;
}
async Task LeaseRenewer(CancellationToken cancellationToken)
{
this.settings.Logger.PartitionManagerInfo(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName,
$"Starting background renewal of app lease with interval: {this.options.RenewInterval}.");
while (!cancellationToken.IsCancellationRequested)
{
try
{
bool renewSucceeded = await RenewLeaseAsync();
if (!renewSucceeded)
{
break;
}
await Task.Delay(this.options.RenewInterval, this.leaseRenewerCancellationTokenSource.Token);
}
catch (OperationCanceledException)
{
// Catch OperationCanceledException to avoid logging an error if the Task.Delay was cancelled.
}
catch (Exception ex)
{
this.settings.Logger.PartitionManagerError(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName,
$"App lease renewer task failed. AppLeaseId: {this.appLeaseId} Exception: {ex}");
}
}
this.settings.Logger.PartitionManagerInfo(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName,
"Background app lease renewer task completed.");
this.settings.Logger.PartitionManagerInfo(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName,
"Lease renewer task completing. Stopping AppLeaseManager.");
await this.StopAppLeaseAsync();
}
async Task<bool> RenewLeaseAsync()
{
bool renewed;
string errorMessage = string.Empty;
try
{
this.settings.Logger.StartingLeaseRenewal(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName,
this.appLeaseId);
await appLeaseContainer.RenewLeaseAsync(appLeaseId);
renewed = true;
}
catch (Exception ex)
{
errorMessage = ex.Message;
if (ex is DurableTaskStorageException storageException
&& (storageException.HttpStatusCode == (int)HttpStatusCode.Conflict
|| storageException.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed))
{
renewed = false;
this.isLeaseOwner = false;
this.settings.Logger.LeaseRenewalFailed(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName,
this.appLeaseId,
ex.Message);
this.settings.Logger.PartitionManagerWarning(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName,
$"AppLeaseManager failed to renew lease. AppLeaseId: {this.appLeaseId} Exception: {ex}");
}
else
{
// Eat any exceptions during renew and keep going.
// Consider the lease as renewed. Maybe lease store outage is causing the lease to not get renewed.
renewed = true;
}
}
this.settings.Logger.LeaseRenewalResult(
this.storageAccountName,
this.taskHub,
this.workerName,
this.appLeaseContainerName,
renewed,
this.appLeaseId,
errorMessage);
return renewed;
}
async Task UpdateOwnerAppIdToCurrentApp()
{
var appLeaseInfo = await GetAppLeaseInfoAsync();
if (appLeaseInfo.OwnerId != this.appLeaseId)
{
appLeaseInfo.OwnerId = this.appLeaseId;
await UpdateAppLeaseInfoBlob(appLeaseInfo);
}
}
async Task UpdateDesiredSwapAppIdToCurrentApp()
{
var appLeaseInfo = await GetAppLeaseInfoAsync();
if (appLeaseInfo.DesiredSwapId != this.appLeaseId)
{
appLeaseInfo.DesiredSwapId = this.appLeaseId;
await UpdateAppLeaseInfoBlob(appLeaseInfo);
}
}
async Task UpdateAppLeaseInfoBlob(AppLeaseInfo appLeaseInfo)
{
string serializedInfo = JsonConvert.SerializeObject(appLeaseInfo);
try
{
await this.appLeaseInfoBlob.UploadTextAsync(serializedInfo);
}
catch (DurableTaskStorageException)
{
// eat any storage exception related to conflict
}
}
async Task<AppLeaseInfo> GetAppLeaseInfoAsync()
{
if (await this.appLeaseInfoBlob.ExistsAsync())
{
await appLeaseInfoBlob.FetchAttributesAsync();
string serializedEventHubInfo = await this.appLeaseInfoBlob.DownloadTextAsync();
return JsonConvert.DeserializeObject<AppLeaseInfo>(serializedEventHubInfo);
}
return null;
}
private class AppLeaseInfo
{
public string OwnerId { get; set; }
public string DesiredSwapId { get; set; }
}
}
}