Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Azure ServiceBus persistent container support #7136

Merged
merged 23 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
3be1e3d
Fix Azure ServiceBus persistent container support
sebastienros Jan 17, 2025
86513bf
Refactor state persistence
sebastienros Jan 18, 2025
1e9de41
Fix tests
sebastienros Jan 22, 2025
97ce49c
PR feedback
sebastienros Jan 23, 2025
ac1e1f5
Fix build
sebastienros Jan 24, 2025
3ebd0da
Merge remote-tracking branch 'origin/main' into sebros/sbpersist
sebastienros Jan 28, 2025
4ffcda7
Test AspireStore
sebastienros Jan 29, 2025
650e3df
Refactor KeyValueStore
sebastienros Jan 29, 2025
d929346
Add tests
sebastienros Jan 29, 2025
fcb23e7
Update src/Aspire.Hosting.Azure.ServiceBus/AzureServiceBusExtensions.cs
sebastienros Jan 29, 2025
d031cd2
Use /obj folder to store files
sebastienros Jan 30, 2025
376fcca
Create ResourcesPreparingEvent
sebastienros Jan 31, 2025
5620c61
Merge remote-tracking branch 'origin/main' into sebros/sbpersist
sebastienros Feb 3, 2025
b8a1025
Remove unused AddPersistentParameter
sebastienros Feb 3, 2025
727f0f0
Only fallback folder on ENV
sebastienros Feb 3, 2025
417c0ff
Fix method documentation
sebastienros Feb 3, 2025
663ee7a
Remove newly added event
sebastienros Feb 4, 2025
33868bc
Merge remote-tracking branch 'origin/main' into sebros/sbpersist
sebastienros Feb 4, 2025
ec769ed
Fix tests
sebastienros Feb 4, 2025
e691cb9
Use temp path for store in functional tests
sebastienros Feb 4, 2025
21808c5
PR feedback
sebastienros Feb 4, 2025
ad785ef
Moving things
sebastienros Feb 4, 2025
1bd23ae
Merge remote-tracking branch 'origin/main' into sebros/sbpersist
sebastienros Feb 4, 2025
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
2 changes: 1 addition & 1 deletion playground/AzureServiceBus/ServiceBus.AppHost/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
serviceBus.RunAsEmulator(configure => configure.ConfigureEmulator(document =>
{
document["UserConfig"]!["Logging"] = new JsonObject { ["Type"] = "Console" };
}));
}).WithLifetime(ContainerLifetime.Persistent));

builder.AddProject<Projects.ServiceBusWorker>("worker")
.WithReference(serviceBus).WaitFor(serviceBus);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

<ItemGroup>
<Compile Include="$(RepoRoot)src\Aspire.Hosting\Utils\PasswordGenerator.cs" Link="Utils\PasswordGenerator.cs" />
<Compile Include="$(SharedDir)AspireStore.cs" Link="Utils\AspireStore.cs" />
<Compile Include="$(SharedDir)SecretsStore.cs" Link="Utils\SecretsStore.cs" />
sebastienros marked this conversation as resolved.
Show resolved Hide resolved
</ItemGroup>

<ItemGroup>
Expand Down
73 changes: 43 additions & 30 deletions src/Aspire.Hosting.Azure.ServiceBus/AzureServiceBusExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,20 +233,10 @@ public static IResourceBuilder<AzureServiceBusResource> RunAsEmulator(this IReso
return builder;
}

// Create a default file mount. This could be replaced by a user-provided file mount.
var configHostFile = Path.Combine(Directory.CreateTempSubdirectory("AspireServiceBusEmulator").FullName, "Config.json");

var defaultConfigFileMount = new ContainerMountAnnotation(
configHostFile,
AzureServiceBusEmulatorResource.EmulatorConfigJsonPath,
ContainerMountType.BindMount,
isReadOnly: true);

builder.WithAnnotation(defaultConfigFileMount);

// Add emulator container

var password = PasswordGenerator.Generate(16, true, true, true, true, 0, 0, 0, 0);
// The password must be at least 8 characters long and contain characters from three of the following four sets: Uppercase letters, Lowercase letters, Base 10 digits, and Symbols
var passwordParameter = ParameterResourceBuilderExtensions.CreateDefaultPasswordParameter(builder.ApplicationBuilder, $"{builder.Resource.Name}-sqledge-pwd", minLower: 1, minUpper: 1, minNumeric: 1);
sebastienros marked this conversation as resolved.
Show resolved Hide resolved

builder
.WithEndpoint(name: "emulator", targetPort: 5672)
Expand All @@ -264,20 +254,57 @@ public static IResourceBuilder<AzureServiceBusResource> RunAsEmulator(this IReso
.WithImageRegistry(ServiceBusEmulatorContainerImageTags.AzureSqlEdgeRegistry)
.WithEndpoint(targetPort: 1433, name: "tcp")
.WithEnvironment("ACCEPT_EULA", "Y")
.WithEnvironment("MSSQL_SA_PASSWORD", password);
.WithEnvironment(context =>
{
context.EnvironmentVariables["MSSQL_SA_PASSWORD"] = passwordParameter;
});

builder.WithAnnotation(new EnvironmentCallbackAnnotation((EnvironmentCallbackContext context) =>
{
var sqlEndpoint = sqlEdgeResource.Resource.GetEndpoint("tcp");

context.EnvironmentVariables.Add("ACCEPT_EULA", "Y");
context.EnvironmentVariables.Add("SQL_SERVER", $"{sqlEndpoint.Resource.Name}:{sqlEndpoint.TargetPort}");
context.EnvironmentVariables.Add("MSSQL_SA_PASSWORD", password);
context.EnvironmentVariables.Add("MSSQL_SA_PASSWORD", passwordParameter);
}));

ServiceBusClient? serviceBusClient = null;
string? queueOrTopicName = null;

var lifetime = ContainerLifetime.Session;

var aspireStore = AspireStore.Create(builder.ApplicationBuilder);

// Deterministic file path for the configuration file
var configHostFile = aspireStore.GetOrCreateFile("Config.json");
sebastienros marked this conversation as resolved.
Show resolved Hide resolved

if (configureContainer != null)
{
var surrogate = new AzureServiceBusEmulatorResource(builder.Resource);
var surrogateBuilder = builder.ApplicationBuilder.CreateResourceBuilder(surrogate);
configureContainer(surrogateBuilder);

if (surrogate.TryGetLastAnnotation<ContainerLifetimeAnnotation>(out var lifetimeAnnotation))
{
lifetime = lifetimeAnnotation.Lifetime;
}
}

sqlEdgeResource = sqlEdgeResource.WithLifetime(lifetime);

var defaultConfigFileMount = new ContainerMountAnnotation(
configHostFile,
AzureServiceBusEmulatorResource.EmulatorConfigJsonPath,
ContainerMountType.BindMount,
isReadOnly: true);

var hasCustomConfigJson = builder.Resource.Annotations.OfType<ContainerMountAnnotation>().Any(v => v.Target == AzureServiceBusEmulatorResource.EmulatorConfigJsonPath);
sebastienros marked this conversation as resolved.
Show resolved Hide resolved

if (!hasCustomConfigJson)
{
builder.WithAnnotation(defaultConfigFileMount);
}

builder.ApplicationBuilder.Eventing.Subscribe<BeforeResourceStartedEvent>(builder.Resource, async (@event, ct) =>
{
var serviceBusEmulatorResources = builder.ApplicationBuilder.Resources.OfType<AzureServiceBusResource>().Where(x => x is { } serviceBusResource && serviceBusResource.IsEmulator);
Expand Down Expand Up @@ -316,15 +343,8 @@ public static IResourceBuilder<AzureServiceBusResource> RunAsEmulator(this IReso
continue;
}

var fileStreamOptions = new FileStreamOptions() { Mode = FileMode.Create, Access = FileAccess.Write };

if (!OperatingSystem.IsWindows())
{
fileStreamOptions.UnixCreateMode =
UnixFileMode.UserRead | UnixFileMode.UserWrite
| UnixFileMode.GroupRead | UnixFileMode.GroupWrite
| UnixFileMode.OtherRead | UnixFileMode.OtherWrite;
}
// Truncate the file since we are going to write to it.
var fileStreamOptions = new FileStreamOptions() { Mode = FileMode.Truncate, Access = FileAccess.Write };

using (var stream = new FileStream(configFileMount.Source!, fileStreamOptions))
{
Expand Down Expand Up @@ -411,13 +431,6 @@ public static IResourceBuilder<AzureServiceBusResource> RunAsEmulator(this IReso

var healthCheckKey = $"{builder.Resource.Name}_check";

if (configureContainer != null)
{
var surrogate = new AzureServiceBusEmulatorResource(builder.Resource);
var surrogateBuilder = builder.ApplicationBuilder.CreateResourceBuilder(surrogate);
configureContainer(surrogateBuilder);
}

// To use the existing ServiceBus health check we would need to know if there is any queue or topic defined.
// We can register a health check for a queue and then no-op if there are no queues. Same for topics.
// If no queues or no topics are defined then the health check will be successful.
Expand Down
30 changes: 30 additions & 0 deletions src/Aspire.Hosting/ParameterResourceBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,36 @@ public static IResourceBuilder<ParameterResource> AddParameter(this IDistributed
return builder.AddParameter(name, () => value, publishValueAsDefault, secret);
}

/// <summary>
/// Creates a new <see cref="ParameterResource"/> that has a generated value using the <paramref name="valueGetter"/>.
/// </summary>
/// <remarks>
/// The value will be saved to the app host project's user secrets store when <see cref="DistributedApplicationExecutionContext.IsRunMode"/> is <c>true</c>
/// and the lifetime of the resource is <see cref="ContainerLifetime.Persistent"/>.
/// </remarks>
/// <param name="builder">Distributed application builder</param>
/// <param name="name">Name of the parameter</param>
/// <param name="valueGetter">A callback returning the default value</param>
/// <returns>The created <see cref="ParameterResource"/>.</returns>
public static ParameterResource AddPersistentParameter(this IDistributedApplicationBuilder builder, string name, Func<string> valueGetter)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentNullException.ThrowIfNull(name);
ArgumentNullException.ThrowIfNull(valueGetter);

var parameterResource = new ParameterResource(name, defaultValue => GetParameterValue(builder.Configuration, name, defaultValue), true)
{
Default = new ConstantParameterDefault(valueGetter)
};

if (builder.ExecutionContext.IsRunMode && builder.AppHostAssembly is not null)
{
parameterResource.Default = new UserSecretsParameterDefault(builder.AppHostAssembly, builder.Environment.ApplicationName, name, parameterResource.Default);
}

return parameterResource;
}

/// <summary>
/// Adds a parameter resource to the application with a value coming from a callback function.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Aspire.Hosting/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@ static Aspire.Hosting.ParameterResourceBuilderExtensions.AddParameter(this Aspir
static Aspire.Hosting.ParameterResourceBuilderExtensions.AddParameter(this Aspire.Hosting.IDistributedApplicationBuilder! builder, string! name, string! value, bool publishValueAsDefault = false, bool secret = false) -> Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ParameterResource!>!
static Aspire.Hosting.ParameterResourceBuilderExtensions.AddParameter(this Aspire.Hosting.IDistributedApplicationBuilder! builder, string! name, System.Func<string!>! valueGetter, bool publishValueAsDefault = false, bool secret = false) -> Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ParameterResource!>!
static Aspire.Hosting.ParameterResourceBuilderExtensions.AddParameterFromConfiguration(this Aspire.Hosting.IDistributedApplicationBuilder! builder, string! name, string! configurationKey, bool secret = false) -> Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ParameterResource!>!
static Aspire.Hosting.ParameterResourceBuilderExtensions.AddPersistentParameter(this Aspire.Hosting.IDistributedApplicationBuilder! builder, string! name, System.Func<string!>! valueGetter) -> Aspire.Hosting.ApplicationModel.ParameterResource!
static Aspire.Hosting.ProjectResourceBuilderExtensions.PublishAsDockerFile<T>(this Aspire.Hosting.ApplicationModel.IResourceBuilder<T!>! builder, System.Action<Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ContainerResource!>!>? configure = null) -> Aspire.Hosting.ApplicationModel.IResourceBuilder<T!>!
static Aspire.Hosting.ProjectResourceBuilderExtensions.WithEndpointsInEnvironment(this Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ProjectResource!>! builder, System.Func<Aspire.Hosting.ApplicationModel.EndpointAnnotation!, bool>! filter) -> Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ProjectResource!>!
Aspire.Hosting.DistributedApplicationExecutionContext.DistributedApplicationExecutionContext(Aspire.Hosting.DistributedApplicationExecutionContextOptions! options) -> void
Expand Down
176 changes: 176 additions & 0 deletions src/Shared/AspireStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Security.Cryptography;
using IdentityModel;
using Microsoft.Extensions.SecretManager.Tools.Internal;

namespace Aspire.Hosting.Utils;

internal sealed class AspireStore : KeyValueStore
sebastienros marked this conversation as resolved.
Show resolved Hide resolved
{
private readonly string _storeBasePath;
private const string StoreFileName = "aspire.json";
private static readonly SearchValues<char> s_invalidChars = SearchValues.Create(['/', '\\', '?', '%', '*', ':', '|', '"', '<', '>', '.', ' ']);

private AspireStore(string basePath)
: base(Path.Combine(basePath, StoreFileName))
{
ArgumentNullException.ThrowIfNull(basePath);

_storeBasePath = basePath;
}

/// <summary>
/// Creates a new instance of <see cref="AspireStore"/> using the provided <paramref name="builder"/>.
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
/// <returns>A new instance of <see cref="AspireStore"/>.</returns>
/// <remarks>
/// The store is created in the following locations:
/// - On Windows: %APPDATA%\Aspire\{applicationHash}\aspire.json
/// - On Mac/Linux: ~/.aspire/{applicationHash}\aspire.json
/// - If none of the above locations are available, the store is created in the directory specified by the ASPIRE_STORE_FALLBACK_DIR environment variable.
/// - If the ASPIRE_STORE_FALLBACK_DIR environment variable is not set, an <see cref="InvalidOperationException"/> is thrown.
///
/// The directory has the permissions set to 700 on Unix systems.
/// </remarks>
public static AspireStore Create(IDistributedApplicationBuilder builder)
{
ArgumentNullException.ThrowIfNull(builder);

const string aspireStoreFallbackDir = "ASPIRE_STORE_FALLBACK_DIR";

var appData = Environment.GetEnvironmentVariable("APPDATA");
var root = appData // On Windows it goes to %APPDATA%\Microsoft\UserSecrets\
?? Environment.GetEnvironmentVariable("HOME") // On Mac/Linux it goes to ~/.microsoft/usersecrets/
?? Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
?? Environment.GetEnvironmentVariable(aspireStoreFallbackDir); // this fallback is an escape hatch if everything else fails

if (string.IsNullOrEmpty(root))
{
throw new InvalidOperationException($"Could not determine an appropriate location for storing user secrets. Set the {aspireStoreFallbackDir} environment variable to a folder where Aspire content should be stored.");
}

var appName = Sanitize(builder.Environment.ApplicationName).ToLowerInvariant();
var appNameHash = builder.Configuration["AppHost:Sha256"]![..10].ToLowerInvariant();

var directoryPath = !string.IsNullOrEmpty(appData)
? Path.Combine(root, "Aspire", $"{appName}.{appNameHash}")
: Path.Combine(root, ".aspire", $"{appName}.{appNameHash}");

return new AspireStore(directoryPath);
}

protected override void EnsureDirectory()
{
var directoryName = Path.GetDirectoryName(FilePath);
if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
{
if (!OperatingSystem.IsWindows())
{
var tempDir = Directory.CreateTempSubdirectory();
tempDir.MoveTo(directoryName);
}
else
{
Directory.CreateDirectory(directoryName);
}
}
}

public string GetOrCreateFileWithContent(string filename, Stream contentStream)
{
// THIS HASN'T BEEN TESTED YET. FOR DISCUSSIONS ONLY.

ArgumentNullException.ThrowIfNullOrWhiteSpace(filename);
ArgumentNullException.ThrowIfNull(contentStream);

EnsureDirectory();

// Strip any folder information from the filename.
filename = Path.GetFileName(filename);

// Delete existing file versions with the same name.
var allFiles = Directory.EnumerateFiles(_storeBasePath, filename + ".*");

foreach (var file in allFiles)
{
try
{
File.Delete(file);
}
catch
{
}
}

// Create a temporary file to write the content to.
var tempFileName = Path.GetTempFileName();

// Write the content to the temporary file.
using (var fileStream = File.OpenWrite(tempFileName))
{
contentStream.CopyTo(fileStream);
}

// Compute the hash of the content.
var hash = SHA256.HashData(File.ReadAllBytes(tempFileName));

// Move the temporary file to the final location.
// TODO: Use System.Buffers.Text implementation when targeting .NET 9.0 or greater
var finalFilePath = Path.Combine(_storeBasePath, filename, ".", Base64Url.Encode(hash).ToLowerInvariant());
File.Move(tempFileName, finalFilePath, overwrite: false);

// If the file already exists, delete the temporary file.
if (File.Exists(tempFileName))
{
File.Delete(tempFileName);
}

return finalFilePath;
}

/// <summary>
/// Creates a file with the provided <paramref name="filename"/> if it does not exist.
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public string GetOrCreateFile(string filename)
{
EnsureDirectory();

// Strip any folder information from the filename.
filename = Path.GetFileName(filename);

var finalFilePath = Path.Combine(_storeBasePath, filename);

if (!File.Exists(finalFilePath))
{
var tempFileName = Path.GetTempFileName();
File.Move(tempFileName, finalFilePath, overwrite: false);
}

return finalFilePath;
}

/// <summary>
/// Removes any unwanted characters from the <paramref name="filename"/>.
/// </summary>
internal static string Sanitize(string filename)
{
return string.Create(filename.Length, filename, static (s, name) =>
{
var nameSpan = name.AsSpan();

for (var i = 0; i < nameSpan.Length; i++)
{
var c = nameSpan[i];

s[i] = s_invalidChars.Contains(c) ? '_' : c;
}
});
}
}
Loading
Loading