Skip to content

Commit 0eafb36

Browse files
authored
Fix hosting exception during startup when CTRL+C (#8886)
1 parent 5b5f4be commit 0eafb36

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/Aspire.Hosting/Dcp/DcpExecutor.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,11 @@ public async Task RunApplicationAsync(CancellationToken cancellationToken = defa
130130

131131
await CreateContainersAndExecutablesAsync(cancellationToken).ConfigureAwait(false);
132132
}
133+
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
134+
{
135+
// This is here so hosting does not throw an exception when CTRL+C during startup.
136+
_logger.LogDebug("Cancellation received during application startup.");
137+
}
133138
catch
134139
{
135140
_shutdownCancellation.Cancel();

tests/Aspire.Hosting.Tests/Dcp/DcpExecutorTests.cs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1200,6 +1200,37 @@ public async Task ContainersArePassedExpectedImagePullPolicy()
12001200
Assert.Equal(ContainerPullPolicy.Missing, explicitMissingContainer.Spec.PullPolicy);
12011201
}
12021202

1203+
[Fact]
1204+
public async Task CancelTokenDuringStartup()
1205+
{
1206+
// Arrange
1207+
var builder = DistributedApplication.CreateBuilder();
1208+
1209+
const int desiredTargetPort = TestKubernetesService.StartOfAutoPortRange - 999;
1210+
builder.AddContainer("database", "image")
1211+
.WithEndpoint(name: "NoPortTargetPortSet", targetPort: desiredTargetPort, env: "NO_PORT_TARGET_PORT_SET", isProxied: true);
1212+
1213+
var kubernetesService = new TestKubernetesService();
1214+
1215+
using var app = builder.Build();
1216+
var distributedAppModel = app.Services.GetRequiredService<DistributedApplicationModel>();
1217+
var dcpEvents = new DcpExecutorEvents();
1218+
var tokenSource = new CancellationTokenSource();
1219+
dcpEvents.Subscribe<OnResourcesPreparedContext>((context) =>
1220+
{
1221+
tokenSource.Cancel();
1222+
return Task.CompletedTask;
1223+
});
1224+
1225+
var appExecutor = CreateAppExecutor(distributedAppModel, kubernetesService: kubernetesService, events: dcpEvents);
1226+
1227+
// Act
1228+
await appExecutor.RunApplicationAsync(tokenSource.Token);
1229+
1230+
// Assert
1231+
Assert.True(tokenSource.IsCancellationRequested);
1232+
}
1233+
12031234
private static void HasKnownCommandAnnotations(IResource resource)
12041235
{
12051236
var commandAnnotations = resource.Annotations.OfType<ResourceCommandAnnotation>().ToList();

0 commit comments

Comments
 (0)