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

Add the ability to stop the Host when one of its BackgroundService instances errors #50569

Merged
merged 17 commits into from
Apr 16, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ public virtual void Dispose() { }
public virtual System.Threading.Tasks.Task StartAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
public virtual System.Threading.Tasks.Task StopAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
}
public enum BackgroundServiceExceptionBehavior
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
{
Ignore,
StopHost
}
[System.ObsoleteAttribute("This type is obsolete and will be removed in a future version. The recommended alternative is Microsoft.Extensions.Hosting.Environments.", false)]
public static partial class EnvironmentName
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ public virtual async Task StopAsync(CancellationToken cancellationToken)
// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executeTask, Task.Delay(Timeout.Infinite, cancellationToken)).ConfigureAwait(false);
}

}

public virtual void Dispose()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.Extensions.Hosting
{
/// <summary>
/// Specifies a behavior that the <see cref="IHost"/> will honor if an
/// unhandled exception occurs in one of its <see cref="BackgroundService"/> instances.
/// </summary>
public enum BackgroundServiceExceptionBehavior
{
/// <summary>
/// Ignore exceptions thrown in <see cref="BackgroundService"/>.
/// </summary>
/// <remarks>
/// If a <see cref="BackgroundService"/> throws an exception, the <see cref="IHost"/> will ignore it.
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
/// The <see cref="BackgroundService"/> is not restarted.
/// </remarks>
Ignore = 0,

/// <summary>
/// Stops the <see cref="IHost"/> instance, and terminates the process.
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
/// </summary>
/// <remarks>
/// If a <see cref="BackgroundService"/> throws an exception, the <see cref="IHost"/> will terminate the process.
/// </remarks>
StopHost = 1
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public partial class HostOptions
{
public HostOptions() { }
public System.TimeSpan ShutdownTimeout { get { throw null; } set { } }
public Microsoft.Extensions.Hosting.BackgroundServiceExceptionBehavior BackgroundServiceExceptionBehavior { get { throw null; } set { } }
}
}
namespace Microsoft.Extensions.Hosting.Internal
Expand Down
6 changes: 6 additions & 0 deletions src/libraries/Microsoft.Extensions.Hosting/src/HostOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ public class HostOptions
/// </summary>
public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(5);

/// <summary>
/// The behavior the <see cref="IHost"/> will follow when any of
/// its <see cref="BackgroundService"/> instances throw an unhandled exception.
/// </summary>
public BackgroundServiceExceptionBehavior BackgroundServiceExceptionBehavior { get; set; }
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved

internal void Initialize(IConfiguration configuration)
{
var timeoutSeconds = configuration["shutdownTimeoutSeconds"];
Expand Down
22 changes: 17 additions & 5 deletions src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,15 @@ public async Task StartAsync(CancellationToken cancellationToken = default)

foreach (IHostedService hostedService in _hostedServices)
{
// Fire IHostedService.Start
await hostedService.StartAsync(combinedCancellationToken).ConfigureAwait(false);

if (hostedService is BackgroundService backgroundService)
{
_ = HandleBackgroundException(backgroundService);
_ = TryStartBackgroundServiceAsync(
backgroundService, combinedCancellationToken);
}
else
{
// Fire IHostedService.Start
await hostedService.StartAsync(combinedCancellationToken).ConfigureAwait(false);
}
}

Expand All @@ -76,15 +79,24 @@ public async Task StartAsync(CancellationToken cancellationToken = default)
_logger.Started();
}

private async Task HandleBackgroundException(BackgroundService backgroundService)
private async Task TryStartBackgroundServiceAsync(
BackgroundService backgroundService, CancellationToken cancellationToken)
{
try
{
// Fire IHostedService.Start
await backgroundService.StartAsync(cancellationToken).ConfigureAwait(false);
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
await backgroundService.ExecuteTask.ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.BackgroundServiceFaulted(ex);
if (_options is { BackgroundServiceExceptionBehavior: BackgroundServiceExceptionBehavior.StopHost })
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
{
_logger.LogCritical(SR.Format(SR.BackgroundServiceExceptionStoppedHost, ex));
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved

await StopAsync(CancellationToken.None).ConfigureAwait(false);
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema

Version 2.0

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:
Expand Down Expand Up @@ -55,7 +55,7 @@
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -117,6 +117,11 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="BackgroundServiceExceptionStoppedHost" xml:space="preserve">
<value>The HostOptions.BackgroundServiceExceptionBehavior is configured to StopHost. A BackgroundService has thrown an unhandled exception, and the IHost instance is stopping. To avoid this behavior, configure this to Ignore; however the BackgroundService will not be restarted.

Error: {0}</value>
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
</data>
<data name="BuildCalled" xml:space="preserve">
<value>Build can only be called once.</value>
</data>
Expand All @@ -129,4 +134,4 @@
<data name="ResolverReturnedNull" xml:space="preserve">
<value>The resolver returned a null IServiceProviderFactory</value>
</data>
</root>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,25 @@ public void HostBuilderConfigureDefaultsInterleavesMissingConfigValues()
Assert.Equal(expectedContentRootPath, env.ContentRootPath);
}

[Fact]
public void HostBuilderCanConfigureBackgroundServiceExceptionBehavior()
{
using IHost host = new HostBuilder()
.ConfigureServices(
services =>
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
services.Configure<HostOptions>(
options =>
options.BackgroundServiceExceptionBehavior =
BackgroundServiceExceptionBehavior.StopHost))
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
.Build();

var options = host.Services.GetRequiredService<IOptions<HostOptions>>();

Assert.Equal(
BackgroundServiceExceptionBehavior.StopHost,
options.Value.BackgroundServiceExceptionBehavior);
}

private class FakeFileProvider : IFileProvider, IDisposable
{
public bool Disposed { get; private set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public void CreateDefaultBuilder_EnablesValidateOnBuild()
[ActiveIssue("https://github.com/dotnet/runtime/issues/34580", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
public async Task CreateDefaultBuilder_ConfigJsonDoesNotReload()
{
var reloadFlagConfig = new Dictionary<string, string>() {{ "hostbuilder:reloadConfigOnChange", "false" }};
var reloadFlagConfig = new Dictionary<string, string>() { { "hostbuilder:reloadConfigOnChange", "false" } };
var appSettingsPath = Path.Combine(Path.GetTempPath(), "appsettings.json");

string SaveRandomConfig()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,67 @@ public async Task WebHostStopAsyncUsesDefaultTimeoutIfNoTokenProvided()
}
}

[Fact]
public async Task HostPropagatesExceptionsThrownWithBackgroundServiceExceptionBehaviorOfStopHost()
{
using IHost host = CreateBuilder()
.ConfigureServices(
services =>
{
services.AddHostedService<AsyncThrowingService>();
services.Configure<HostOptions>(
options =>
options.BackgroundServiceExceptionBehavior =
BackgroundServiceExceptionBehavior.StopHost);
})
.Build();

await host.StartAsync();

var lifetime = host.Services.GetRequiredService<IHostApplicationLifetime>();
var wasStoppingCalled = false;
lifetime.ApplicationStopping.Register(() => wasStoppingCalled = true);
var wasStoppedCalled = false;
lifetime.ApplicationStopped.Register(() => wasStoppedCalled = true);

Assert.True(
wasStoppingCalled,
$"The {nameof(AsyncThrowingService)} should have thrown, calling Host.StopAsync, gracefully stopping the host.");
Assert.True(
wasStoppedCalled,
$"The {nameof(AsyncThrowingService)} should have thrown, calling Host.StopAsync, gracefully stopping the host.");
}

[Fact]
public void HostHandlesExceptionsThrownWithBackgroundServiceExceptionBehaviorOfIgnore()
{
var backgroundDelayTaskSource = new TaskCompletionSource<bool>();

using IHost host = CreateBuilder()
.ConfigureServices(
services =>
{
services.AddHostedService(
_ => new AsyncThrowingService(backgroundDelayTaskSource.Task));

services.PostConfigure<HostOptions>(
options =>
options.BackgroundServiceExceptionBehavior =
BackgroundServiceExceptionBehavior.Ignore);
})
.Build();

var lifetime = host.Services.GetRequiredService<IHostApplicationLifetime>();
var wasStoppingCalled = false;
lifetime.ApplicationStopping.Register(() => wasStoppingCalled = true);

host.Start();

backgroundDelayTaskSource.SetResult(true);
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved

Assert.False(wasStoppingCalled);
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
}

[Fact]
public void HostApplicationLifetimeEventsOrderedCorrectlyDuringShutdown()
{
Expand Down Expand Up @@ -1373,7 +1434,9 @@ public ValueTask DisposeAsync()

private class AsyncThrowingService : BackgroundService
{
private readonly Task _executeDelayTask;
private readonly Task? _executeDelayTask;

public AsyncThrowingService() { }
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved

public AsyncThrowingService(Task executeDelayTask)
{
Expand All @@ -1382,9 +1445,13 @@ public AsyncThrowingService(Task executeDelayTask)

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await _executeDelayTask;
while (true)
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
{
if (_executeDelayTask is { })
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
await _executeDelayTask;

throw new Exception("Background Exception");
throw new Exception("Background Exception");
}
}
}
}
Expand Down