Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
236 changes: 227 additions & 9 deletions src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@
namespace DurableTask.AzureStorage.Storage
{
using System;
using System.Collections.Concurrent;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Data.Tables;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Specialized;
using Azure.Storage.Queues;
using DurableTask.AzureStorage.Http;
using DurableTask.AzureStorage.Monitoring;
Expand All @@ -27,8 +31,120 @@ class AzureStorageClient
readonly BlobServiceClient blobClient;
readonly QueueServiceClient queueClient;
readonly TableServiceClient tableClient;
readonly MigrationSasManager? migration;
readonly bool isMigrationActive;
readonly object? initializationLock;
Task? migrationInitialization;
readonly QueueClientOptions? sasQueueOptions;
readonly TableClientOptions? sasTableOptions;
readonly BlobClientOptions? sasBlobOptions;
readonly ConcurrentDictionary<string, QueueClient>? sasQueues;
readonly ConcurrentDictionary<string, TableClient>? sasTables;
readonly ConcurrentDictionary<string, BlobContainerClient>? sasContainers;

public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings)
public event Action? MigrationEnding;
public bool IsMigrationActive => this.isMigrationActive;
public bool IsMigrationEnding => this.isMigrationActive && this.migration!.IsMigrationEnding;

public async Task InitializeMigrationAsync(bool refresh = false)
{
if (!this.IsMigrationActive)
{
return;
}
Task initialization;
bool refreshCachedInitialization;
lock (this.initializationLock!)
{
// New or in-progress initialization already refreshes credentials and starts the loop.
refreshCachedInitialization = refresh && this.migrationInitialization?.Status == TaskStatus.RanToCompletion;
// Run on the thread pool because synchronous SDK wrapper properties also call this method.
initialization = this.migrationInitialization ??= Task.Run(this.InitializeMigrationCoreAsync);
}
try
{
await initialization.ConfigureAwait(false);
}
catch
{
lock (this.initializationLock!)
{
// Do not clear a newer initialization started by another caller.
if (ReferenceEquals(this.migrationInitialization, initialization))
{
this.migrationInitialization = null;
}
}
throw;
}
if (refreshCachedInitialization)
{
// A completed initialization may belong to a stopped service; refresh and restart its loop.
await this.InitializeMigrationCoreAsync();
}
}

public Task StopMigrationTokenRefreshAsync()
{
return this.migration?.StopRefreshing() ?? Task.CompletedTask;
}

async Task InitializeMigrationCoreAsync()
{
await this.migration!.RefreshAsync(CancellationToken.None).ConfigureAwait(false);
_ = this.migration!.StartRefreshLoop();
}

public void EnsureAccess()
{
if (this.isMigrationActive)
{
this.InitializeMigrationAsync().GetAwaiter().GetResult();
this.migration!.EnsureAccess();
}
}

public void ThrowIfMigrationResourceDeletion()
{
this.EnsureAccess();
if (this.isMigrationActive)
{
throw new OrchestrationServiceUnavailableException("Task hub resource deletion is not supported during migration.");
}
}

public QueueClient GetQueueClient(QueueClient original)
{
this.EnsureAccess();
return !this.isMigrationActive ? original : this.sasQueues!.GetOrAdd(
original.Name,
name => new QueueClient(original.Uri, this.migration!.GetCredential('q', name), this.sasQueueOptions));
}

public TableClient GetTableClient(TableClient original)
{
this.EnsureAccess();
return !this.isMigrationActive ? original : this.sasTables!.GetOrAdd(
original.Name,
name => new TableClient(original.Uri, this.migration!.GetCredential('t', name), this.sasTableOptions));
}

public BlobContainerClient GetBlobContainerClient(BlobContainerClient original)
{
this.EnsureAccess();
return !this.isMigrationActive ? original : this.sasContainers!.GetOrAdd(
original.Name,
name => new BlobContainerClient(original.Uri, this.migration!.GetCredential('b', name), this.sasBlobOptions));
}

public BlockBlobClient GetBlockBlobClient(BlockBlobClient original)
{
this.EnsureAccess();
return !this.isMigrationActive ? original : this.GetBlobContainerClient(
this.blobClient.GetBlobContainerClient(original.BlobContainerName)).GetBlockBlobClient(original.Name);
}

public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings, Guid? migrationId = null)
{
if (settings == null)
{
Expand All @@ -40,23 +156,107 @@ public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings)
throw new ArgumentException("Storage account client provider is not specified.", nameof(settings));
}

this.isMigrationActive = migrationId.HasValue;
this.Settings = settings;
this.Stats = new AzureStorageOrchestrationServiceStats();

var throttlingPolicy = new ThrottlingHttpPipelinePolicy(this.Settings.MaxStorageOperationConcurrency);
var timeoutPolicy = new LeaseTimeoutHttpPipelinePolicy(this.Settings.LeaseRenewInterval);
var monitoringPolicy = new MonitoringHttpPipelinePolicy(this.Stats);

this.queueClient = CreateClient(settings.StorageAccountClientProvider.Queue, ConfigureQueueClientPolicies);
QueueClientOptions? queueManagementOptions = null;
BlobClientOptions? blobManagementOptions = null;
TableClientOptions? tableManagementOptions = null;
this.queueClient = CreateClient(
settings.StorageAccountClientProvider.Queue,
options =>
{
queueManagementOptions = options;
ConfigureQueueClientPolicies(options);
});
if (settings.HasTrackingStoreStorageAccount)
{
this.blobClient = CreateClient(settings.TrackingServiceClientProvider!.Blob, ConfigureClientPolicies);
this.tableClient = CreateClient(settings.TrackingServiceClientProvider!.Table, ConfigureClientPolicies);
this.blobClient = CreateClient(
settings.TrackingServiceClientProvider!.Blob,
options =>
{
blobManagementOptions = options;
ConfigureClientPolicies(options);
});
this.tableClient = CreateClient(
settings.TrackingServiceClientProvider!.Table,
options =>
{
tableManagementOptions = options;
options.Diagnostics.IsLoggingContentEnabled = false;
ConfigureClientPolicies(options);
});
}
else
{
this.blobClient = CreateClient(settings.StorageAccountClientProvider.Blob, ConfigureClientPolicies);
this.tableClient = CreateClient(settings.StorageAccountClientProvider.Table, ConfigureClientPolicies);
this.blobClient = CreateClient(
settings.StorageAccountClientProvider.Blob,
options =>
{
blobManagementOptions = options;
ConfigureClientPolicies(options);
});
this.tableClient = CreateClient(
settings.StorageAccountClientProvider.Table,
options =>
{
tableManagementOptions = options;
options.Diagnostics.IsLoggingContentEnabled = false;
ConfigureClientPolicies(options);
});
}

if (migrationId.HasValue)
{
this.initializationLock = new object();
this.sasQueues = new ConcurrentDictionary<string, QueueClient>();
this.sasTables = new ConcurrentDictionary<string, TableClient>();
this.sasContainers = new ConcurrentDictionary<string, BlobContainerClient>();

this.migration = new MigrationSasManager(
settings,
migrationId.Value,
this.blobClient,
this.queueClient,
this.tableClient,
(settings.TrackingServiceClientProvider ?? settings.StorageAccountClientProvider).Table,
() => this.MigrationEnding?.Invoke());

// Retry authentication failures once with a refreshed SAS.
MigrationSasRetryPolicy sasRetry = new MigrationSasRetryPolicy(this.migration);

// Keep migration policies off options shared with other clients.
this.sasQueueOptions = CopyTransportOptions(
queueManagementOptions!,
new QueueClientOptions
{
Audience = queueManagementOptions!.Audience,
GeoRedundantSecondaryUri = queueManagementOptions.GeoRedundantSecondaryUri,
});
this.sasQueueOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall);
ConfigureQueueClientPolicies(this.sasQueueOptions);
this.sasQueueOptions.AddPolicy(new MigrationRequestPolicy(this.migration, useDelegationVersion: true), HttpPipelinePosition.PerRetry);
this.sasTableOptions = CopyTransportOptions(
tableManagementOptions!,
new TableClientOptions { Audience = tableManagementOptions!.Audience });
this.sasTableOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall);
ConfigureClientPolicies(this.sasTableOptions);
this.sasTableOptions.AddPolicy(new MigrationRequestPolicy(this.migration, useDelegationVersion: true), HttpPipelinePosition.PerRetry);
this.sasBlobOptions = CopyTransportOptions(
blobManagementOptions!,
new BlobClientOptions
{
Audience = blobManagementOptions!.Audience,
GeoRedundantSecondaryUri = blobManagementOptions.GeoRedundantSecondaryUri,
Comment on lines +254 to +255
});
this.sasBlobOptions.AddPolicy(sasRetry, HttpPipelinePosition.PerCall);
ConfigureClientPolicies(this.sasBlobOptions);
this.sasBlobOptions.AddPolicy(new MigrationRequestPolicy(this.migration), HttpPipelinePosition.PerRetry);
}

void ConfigureClientPolicies<TClientOptions>(TClientOptions options) where TClientOptions : ClientOptions
Expand Down Expand Up @@ -129,7 +329,7 @@ await args.Queue.UpdateMessageAsync(
};
}

ConfigureClientPolicies(options);
ConfigureClientPolicies(options);
}
}

Expand All @@ -145,12 +345,12 @@ await args.Queue.UpdateMessageAsync(

public Blob GetBlobReference(string container, string blobName)
{
return new Blob(this.blobClient, container, blobName);
return new Blob(this, this.blobClient, container, blobName);
}

internal Blob GetBlobReference(Uri blobUri)
{
return new Blob(this.blobClient, blobUri);
return new Blob(this, this.blobClient, blobUri);
}

public BlobContainer GetBlobContainerReference(string container)
Expand Down Expand Up @@ -182,5 +382,23 @@ static TClient CreateClient<TClient, TClientOptions>(

return storageProvider.CreateClient(options);
}

static TOptions CopyTransportOptions<TOptions>(ClientOptions source, TOptions destination) where TOptions : ClientOptions
{
destination.Transport = source.Transport;
destination.Retry.Mode = source.Retry.Mode;
destination.Retry.Delay = source.Retry.Delay;
destination.Retry.MaxDelay = source.Retry.MaxDelay;

// Limit request duration during migration by disabling SDK retries.
// Authentication failures still get one refresh and retry.
destination.Retry.MaxRetries = 0;
destination.Retry.NetworkTimeout = source.Retry.NetworkTimeout;
destination.Diagnostics.ApplicationId = source.Diagnostics.ApplicationId;
destination.Diagnostics.IsLoggingEnabled = source.Diagnostics.IsLoggingEnabled;
destination.Diagnostics.IsLoggingContentEnabled = source.Diagnostics.IsLoggingContentEnabled;
destination.Diagnostics.IsDistributedTracingEnabled = false;
return destination;
}
}
}
20 changes: 13 additions & 7 deletions src/DurableTask.AzureStorage/Storage/Blob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,31 +25,37 @@ namespace DurableTask.AzureStorage.Storage

class Blob
{
readonly BlockBlobClient blockBlobClient;
readonly AzureStorageClient azureStorageClient;
readonly BlockBlobClient originalBlockBlobClient;
BlockBlobClient? cachedBlockBlobClient;
BlockBlobClient blockBlobClient => Volatile.Read(ref this.cachedBlockBlobClient)
?? LazyInitializer.EnsureInitialized(ref this.cachedBlockBlobClient, () => this.azureStorageClient.GetBlockBlobClient(this.originalBlockBlobClient))!;

public Blob(BlobServiceClient blobServiceClient, string containerName, string blobName)
public Blob(AzureStorageClient azureStorageClient, BlobServiceClient blobServiceClient, string containerName, string blobName)
{
this.blockBlobClient = blobServiceClient
this.azureStorageClient = azureStorageClient;
this.originalBlockBlobClient = blobServiceClient
.GetBlobContainerClient(containerName)
.GetBlockBlobClient(blobName);
}

public Blob(BlobServiceClient blobServiceClient, Uri blobUri)
public Blob(AzureStorageClient azureStorageClient, BlobServiceClient blobServiceClient, Uri blobUri)
{
if (!blobUri.AbsoluteUri.StartsWith(blobServiceClient.Uri.AbsoluteUri, StringComparison.Ordinal))
{
throw new ArgumentException("Blob is not present in the storage account", nameof(blobUri));
}

var builder = new BlobUriBuilder(blobUri);
this.blockBlobClient = blobServiceClient
this.azureStorageClient = azureStorageClient;
this.originalBlockBlobClient = blobServiceClient
.GetBlobContainerClient(builder.BlobContainerName)
.GetBlockBlobClient(builder.BlobName);
}

public string Name => this.blockBlobClient.Name;
public string Name => this.originalBlockBlobClient.Name;

public Uri Uri => this.blockBlobClient.Uri;
public Uri Uri => this.originalBlockBlobClient.Uri;

public async Task<bool> ExistsAsync(CancellationToken cancellationToken = default)
{
Expand Down
Loading
Loading