Skip to content
Merged
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
66 changes: 49 additions & 17 deletions src/Aspire.Hosting/ApplicationModel/HostUrl.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using Aspire.Hosting.Dcp;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
Expand All @@ -17,7 +18,7 @@ public record HostUrl(string Url) : IExpressionValue, IValueProvider, IManifestE
string IManifestExpressionProvider.ValueExpression => Url;

// Returns the url
ValueTask<string?> IValueProvider.GetValueAsync(System.Threading.CancellationToken cancellationToken) => ((IValueProvider)this).GetValueAsync(new(), cancellationToken);
ValueTask<string?> IValueProvider.GetValueAsync(CancellationToken cancellationToken) => ((IValueProvider)this).GetValueAsync(new(), cancellationToken);

// Returns the url
async ValueTask<string?> IValueProvider.GetValueAsync(ValueProviderContext context, CancellationToken cancellationToken)
Expand All @@ -39,7 +40,7 @@ public record HostUrl(string Url) : IExpressionValue, IValueProvider, IManifestE
try
{
var uri = new UriBuilder(Url);
if (uri.Host is "localhost" or "127.0.0.1" or "[::1]")
if (IsLocalHost(uri.Host))
{
if (context.ExecutionContext?.IsRunMode == true)
{
Expand All @@ -52,37 +53,40 @@ public record HostUrl(string Url) : IExpressionValue, IValueProvider, IManifestE
var infoService = context.ExecutionContext.ServiceProvider.GetRequiredService<IDcpDependencyCheckService>();
var dcpInfo = await infoService.GetDcpInfoAsync(cancellationToken: cancellationToken).ConfigureAwait(false);

// Determine what hostname means that we want to contact the host machine from the container. If using the new tunnel feature, this needs to be the address of the tunnel instance.
// Otherwise we want to try and determine the container runtime appropriate hostname (host.docker.internal or host.containers.internal).
uri.Host = options.Value.EnableAspireContainerTunnel? KnownHostNames.DefaultContainerTunnelHostName : dcpInfo?.Containers?.ContainerHostName ?? KnownHostNames.DockerDesktopHostBridge;
var containerHostName = dcpInfo?.Containers?.ContainerHostName ?? KnownHostNames.DockerDesktopHostBridge;
var model = context.ExecutionContext.ServiceProvider.GetService<DistributedApplicationModel>();
EndpointReference? targetEndpoint = null;

if (options.Value.EnableAspireContainerTunnel && model is { })
{
// If we're running with the container tunnel enabled, we need to lookup the port on the tunnel that corresponds to the
// target port on the host machine.
var targetEndpoint = model.Resources.Where(r => !r.IsContainer())

targetEndpoint = model.Resources.Where(r => !r.IsContainer())
.OfType<IResourceWithEndpoints>()
.Select(r =>
{
// Find if the resource has a host endpoint with a port matching the one from the request
if (r.GetEndpoints(KnownNetworkIdentifiers.LocalhostNetwork).FirstOrDefault(ep => ep.Port == uri.Port) is EndpointReference ep)
if (r.Annotations.OfType<EndpointAnnotation>().FirstOrDefault(ep => MatchesHostPort(ep, uri.Port)) is EndpointAnnotation ep)
{
// Return the corresponding endpoint for the container network context. This will be used to determine the port to use when connecting from the container to the host machine.
return r.GetEndpoint(ep.EndpointName, networkContext);
return r.GetEndpoint(ep.Name, networkContext);
}

return null;
})
.Where(ep => ep is not null)
.FirstOrDefault();

if (targetEndpoint is { })
{
// If we found a container endpoint, remap the requested port
uri.Port = targetEndpoint.Port;
}
.FirstOrDefault(ep => ep is not null);
}

if (targetEndpoint is { })
{
uri.Host = KnownHostNames.DefaultContainerTunnelHostName;
var port = await targetEndpoint.Property(EndpointProperty.Port).GetValueAsync(context, cancellationToken).ConfigureAwait(false);
uri.Port = int.Parse(port!, CultureInfo.InvariantCulture);
}
else
{
uri.Host = containerHostName;
}

retval = uri.ToString();
Expand Down Expand Up @@ -121,4 +125,32 @@ public record HostUrl(string Url) : IExpressionValue, IValueProvider, IManifestE

return new(retval);
}

internal static bool TryGetLocalHostPort(string url, out int port)
{
port = 0;

try
{
var uri = new UriBuilder(url);
if (!IsLocalHost(uri.Host))
{
return false;
}

port = uri.Port;
return true;
}
catch (UriFormatException)
{
return false;
}
}

internal static bool MatchesHostPort(EndpointAnnotation endpoint, int port)
{
return endpoint.DefaultNetworkID == KnownNetworkIdentifiers.LocalhostNetwork && endpoint.Port == port;
}

private static bool IsLocalHost(string host) => host is "localhost" or "127.0.0.1" or "::1" or "[::1]";
}
51 changes: 48 additions & 3 deletions src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1462,7 +1462,7 @@ private static async Task GatherDirectDependenciesAsync(

foreach (var value in rawValues)
{
CollectDependenciesFromValue(value, dependencies, newDependencies, visited);
CollectDependenciesFromValue(value, dependencies, newDependencies, visited, executionContext);
}
}

Expand Down Expand Up @@ -1572,13 +1572,23 @@ private static void CollectAnnotationDependencies(IResource resource, HashSet<IR
/// <summary>
/// Recursively collects resource dependencies from a value using <see cref="IValueWithReferences"/>.
/// </summary>
private static void CollectDependenciesFromValue(object? value, HashSet<IResource> dependencies, HashSet<IResource> newDependencies, HashSet<object> visitedValues)
private static void CollectDependenciesFromValue(
object? value,
HashSet<IResource> dependencies,
HashSet<IResource> newDependencies,
HashSet<object> visitedValues,
DistributedApplicationExecutionContext executionContext)
{
if (value is null || !visitedValues.Add(value))
{
return;
}

if (value is HostUrl hostUrl)
{
CollectHostUrlDependencies(hostUrl, dependencies, newDependencies, executionContext);
}

// Direct resource references
if (value is IResource resource)
{
Expand All @@ -1603,7 +1613,42 @@ private static void CollectDependenciesFromValue(object? value, HashSet<IResourc
{
foreach (var reference in valueWithReferences.References)
{
CollectDependenciesFromValue(reference, dependencies, newDependencies, visitedValues);
CollectDependenciesFromValue(reference, dependencies, newDependencies, visitedValues, executionContext);
}
}
}

private static void CollectHostUrlDependencies(
HostUrl hostUrl,
HashSet<IResource> dependencies,
HashSet<IResource> newDependencies,
DistributedApplicationExecutionContext executionContext)
{
if (!HostUrl.TryGetLocalHostPort(hostUrl.Url, out var port))
{
return;
}

DistributedApplicationModel? model;
try
{
model = executionContext.ServiceProvider.GetService<DistributedApplicationModel>();
}
catch (InvalidOperationException)
{
return;
}

if (model is null)
{
return;
}

foreach (var resource in model.Resources.Where(r => !r.IsContainer()).OfType<IResourceWithEndpoints>())
{
if (resource.Annotations.OfType<EndpointAnnotation>().Any(ep => HostUrl.MatchesHostPort(ep, port)) && dependencies.Add(resource))
{
newDependencies.Add(resource);
}
}
}
Expand Down
75 changes: 75 additions & 0 deletions tests/Aspire.Hosting.Tests/Dcp/DcpExecutorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#pragma warning disable ASPIREEXTENSION001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
#pragma warning disable ASPIRECERTIFICATES001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
using System.Collections.Concurrent;
using System.Globalization;
using System.IO.Pipelines;
using System.Security.Cryptography.X509Certificates;
Expand Down Expand Up @@ -2839,6 +2840,79 @@ async ValueTask AssertEndpoint(IResourceWithEndpoints resource, string name, Net
}
}

[Fact]
public async Task ContainerHostUrlWithoutMatchingHostEndpointUsesContainerHostBridge()
{
var builder = DistributedApplication.CreateBuilder();

builder.AddContainer("aContainer", "image")
.WithEnvironment("URL", new HostUrl("https://localhost:17092/path"));

var kubernetesService = new TestKubernetesService();
using var app = builder.Build();
var distributedAppModel = app.Services.GetRequiredService<DistributedApplicationModel>();

var dcpOptions = new DcpOptions
{
EnableAspireContainerTunnel = true,
};

var appExecutor = CreateAppExecutor(distributedAppModel, kubernetesService: kubernetesService, dcpOptions: dcpOptions);
await appExecutor.RunApplicationAsync();

var dcpContainer = Assert.Single(kubernetesService.CreatedResources.OfType<Container>(), c => c.AppModelResourceName == "aContainer");
Assert.NotNull(dcpContainer.Spec.Env);
var url = Assert.Single(dcpContainer.Spec.Env, e => e.Name == "URL").Value;
Assert.Equal("https://host.docker.internal:17092/path", url);

Assert.DoesNotContain(kubernetesService.CreatedResources.OfType<Service>(),
s => s.Metadata.Annotations.ContainsKey(CustomResource.ContainerTunnelInstanceName));
}

[Fact]
public async Task ContainerHostUrlMatchingHostEndpointUsesTunnelPort()
{
var builder = DistributedApplication.CreateBuilder();

var executable = builder.AddExecutable("anExecutable", "command", "")
.WithEndpoint(name: "http", targetPort: 1234, port: 5678, isProxied: true);

builder.AddContainer("aContainer", "image")
.WithEnvironment("URL", new HostUrl("https://localhost:5678/path"));

var kubernetesService = new TestKubernetesService();
using var app = builder.Build();
var distributedAppModel = app.Services.GetRequiredService<DistributedApplicationModel>();

var failedResources = new ConcurrentBag<string>();
var events = new DcpExecutorEvents();
events.Subscribe<OnResourceFailedToStartContext>(context =>
{
failedResources.Add(context.Resource.Name);
return Task.CompletedTask;
});

var dcpOptions = new DcpOptions
{
EnableAspireContainerTunnel = true,
};

var appExecutor = CreateAppExecutor(distributedAppModel, kubernetesService: kubernetesService, dcpOptions: dcpOptions, events: events);
await appExecutor.RunApplicationAsync();

Assert.DoesNotContain("aContainer", failedResources);

var dcpContainer = Assert.Single(kubernetesService.CreatedResources.OfType<Container>(), c => c.AppModelResourceName == "aContainer");
var tunnelService = Assert.Single(kubernetesService.CreatedResources.OfType<Service>(),
s => s.AppModelResourceName == executable.Resource.Name
&& s.EndpointName == "http"
&& s.Metadata.Annotations.ContainsKey(CustomResource.ContainerTunnelInstanceName));

Assert.NotNull(dcpContainer.Spec.Env);
var url = Assert.Single(dcpContainer.Spec.Env, e => e.Name == "URL").Value;
Assert.Equal($"https://{KnownHostNames.DefaultContainerTunnelHostName}:{tunnelService.AllocatedPort}/path", url);
}

// Verifies that environment value callbacks are invoked only once per container startup.
[Fact]
public async Task EnvironmentCallbacksInvokedOnceOnContainer()
Expand Down Expand Up @@ -3350,6 +3424,7 @@ private static DcpExecutor CreateAppExecutor(
{
ServiceProvider = new TestServiceProvider(configuration)
.AddService<IDeveloperCertificateService>(developerCertificateService)
.AddService(distributedAppModel)
.AddService(Options.Create(dcpOptions))
.AddService(resourceLoggerService)
});
Expand Down
45 changes: 41 additions & 4 deletions tests/Aspire.Hosting.Tests/ExpressionResolverTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,11 @@ public async Task ExpressionResolverGeneratesCorrectEndpointStrings(string exprN

[Theory]
[InlineData(false, true, "http://localhost:18889", "http://localhost:18889")]
[InlineData(true, true, "http://localhost:18889", "http://aspire.dev.internal:18889")]
[InlineData(true, true, "http://localhost:18889", "http://host.docker.internal:18889")]
[InlineData(false, true, "http://127.0.0.1:18889", "http://127.0.0.1:18889")]
[InlineData(true, true, "http://127.0.0.1:18889", "http://aspire.dev.internal:18889")]
[InlineData(true, true, "http://127.0.0.1:18889", "http://host.docker.internal:18889")]
[InlineData(false, true, "http://[::1]:18889", "http://[::1]:18889")]
[InlineData(true, true, "http://[::1]:18889", "http://aspire.dev.internal:18889")]
[InlineData(true, true, "http://[::1]:18889", "http://host.docker.internal:18889")]
[InlineData(false, false, "http://localhost:18889", "http://localhost:18889")]
[InlineData(true, false, "http://localhost:18889", "http://host.docker.internal:18889")]
[InlineData(false, false, "http://127.0.0.1:18889", "http://127.0.0.1:18889")]
Expand Down Expand Up @@ -183,9 +183,46 @@ public async Task HostUrlPropertyGetsResolved(bool targetIsContainer, bool withT
Assert.Equal(expectedValue, config["envname"]);
}

[Fact]
public async Task ContainerHostUrlIgnoresMatchingNonHostEndpoint()
{
var builder = DistributedApplication.CreateBuilder();

var nonHostEndpoint = new EndpointAnnotation(
System.Net.Sockets.ProtocolType.Tcp,
KnownNetworkIdentifiers.DefaultAspireContainerNetwork,
uriScheme: "http",
name: "internal",
port: 18889,
targetPort: 18889);

nonHostEndpoint.AllAllocatedEndpoints.AddOrUpdateAllocatedEndpoint(
KnownNetworkIdentifiers.DefaultAspireContainerNetwork,
new AllocatedEndpoint(
nonHostEndpoint,
KnownHostNames.DefaultContainerTunnelHostName,
47092,
EndpointBindingMode.SingleAddress,
targetPortExpression: "47092",
KnownNetworkIdentifiers.DefaultAspireContainerNetwork));

builder.AddResource(new TestHostResource("nonHost"))
.WithAnnotation(nonHostEndpoint);

var test = builder.AddContainer("testSource", "someimage")
.WithEnvironment("envname", new HostUrl("http://localhost:18889/path"));

var testServiceProvider = new TestServiceProvider();
testServiceProvider.AddService(Options.Create(new DcpOptions() { EnableAspireContainerTunnel = true }));
testServiceProvider.AddService(new DistributedApplicationModel(builder.Resources));

var config = await EnvironmentVariableEvaluator.GetEnvironmentVariablesAsync(test.Resource, DistributedApplicationOperation.Run, testServiceProvider).DefaultTimeout();
Assert.Equal("http://host.docker.internal:18889/path", config["envname"]);
}

[Theory]
[InlineData(false, true, "http://localhost:18889")]
[InlineData(true, true, "http://aspire.dev.internal:18889")]
[InlineData(true, true, "http://host.docker.internal:18889")]
[InlineData(false, false, "http://localhost:18889")]
[InlineData(true, false, "http://host.docker.internal:18889")]
public async Task HostUrlPropertyGetsResolvedInOtlpExporterEndpoint(bool container, bool withTunnel, string expectedValue)
Expand Down
Loading
Loading