-
Notifications
You must be signed in to change notification settings - Fork 22
Gracefully shutdown app #1543
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
Open
martinothamar
wants to merge
1
commit into
main
Choose a base branch
from
chore/graceful-shutdown
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+82
−0
Open
Gracefully shutdown app #1543
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,6 +6,7 @@ | |
| using Altinn.App.Api.Helpers.Patch; | ||
| using Altinn.App.Api.Infrastructure.Filters; | ||
| using Altinn.App.Api.Infrastructure.Health; | ||
| using Altinn.App.Api.Infrastructure.Lifetime; | ||
| using Altinn.App.Api.Infrastructure.Middleware; | ||
| using Altinn.App.Api.Infrastructure.Telemetry; | ||
| using Altinn.App.Core.Constants; | ||
|
|
@@ -124,6 +125,8 @@ IWebHostEnvironment env | |
| options.AllowSynchronousIO = true; | ||
| }); | ||
|
|
||
| ConfigureGracefulShutdown(services); | ||
|
|
||
| // HttpClients for platform functionality. Registered as HttpClient so default HttpClientFactory is used | ||
| services.AddHttpClient<AuthorizationApiClient>(); | ||
|
|
||
|
|
@@ -546,4 +549,34 @@ IHostEnvironment env | |
|
|
||
| return $"InstrumentationKey={key}"; | ||
| } | ||
|
|
||
| private static void ConfigureGracefulShutdown(IServiceCollection services) | ||
| { | ||
| // Need to coordinate graceful shutdown (let's assume k8s as the scheduler/runtime): | ||
| // - deployment is configured with a terminationGracePeriod of 30s (default timeout before SIGKILL) | ||
| // - k8s flow of information is eventually consistent. | ||
| // it takes time for knowledge of SIGTERM on the worker node to propagate to e.g. networking layers | ||
| // (k8s Service -> Endspoints rotation. It takes time to be taken out of Endpoint rotation) | ||
| // - we want to gracefully drain ASP.NET core for requests, leaving some time for active requests to complete | ||
| // This leaves us with the following sequence of events | ||
| // - container receives SIGTERM | ||
| // - `AppHostLifetime` intercepts SIGTERM and delays for `shutdownDelay` | ||
| // - `AppHostLifetime` calls `IHostApplicationLifetime.StopApplication`, to start ASP.NET Core shutdown process | ||
| // - ASP.NET Core will spend a maximum of `shutdownTimeout` trying to drain active requests | ||
| // (cancelable requests can combine cancellation tokens with `IHostApplicationLifetime.ApplicationStopping`) | ||
| // - If ASP.NET Core completes shutdown within `shutdownTimeout`, everything is fine | ||
| // - If ASP.NET Core is stuck or in some way can't terminate, kubelet will eventually SIGKILL | ||
| var shutdownDelay = TimeSpan.FromSeconds(5); | ||
| var shutdownTimeout = TimeSpan.FromSeconds(20); | ||
|
|
||
| services.AddSingleton<IHostLifetime>(serviceProvider => | ||
| { | ||
| var logger = serviceProvider.GetRequiredService<ILogger<AppHostLifetime>>(); | ||
| var env = serviceProvider.GetRequiredService<IHostEnvironment>(); | ||
| var lifetime = serviceProvider.GetRequiredService<IHostApplicationLifetime>(); | ||
| return new AppHostLifetime(logger, env, lifetime, shutdownDelay); | ||
| }); | ||
|
|
||
| services.Configure<HostOptions>(options => options.ShutdownTimeout = shutdownTimeout); | ||
| } | ||
|
Comment on lines
+552
to
+581
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Gate by environment; make idempotent values configurable; fix typo
- private static void ConfigureGracefulShutdown(IServiceCollection services)
+ private static void ConfigureGracefulShutdown(IServiceCollection services, IHostEnvironment env)
{
- // Need to coordinate graceful shutdown (let's assume k8s as the scheduler/runtime):
+ // Need to coordinate graceful shutdown (let's assume k8s as the scheduler/runtime):
// - deployment is configured with a terminationGracePeriod of 30s (default timeout before SIGKILL)
// - k8s flow of information is eventually consistent.
- // it takes time for knowledge of SIGTERM on the worker node to propagate to e.g. networking layers
- // (k8s Service -> Endspoints rotation. It takes time to be taken out of Endpoint rotation)
+ // it takes time for knowledge of SIGTERM on the worker node to propagate to e.g. networking layers
+ // (k8s Service -> Endpoints rotation. It takes time to be taken out of Endpoint rotation)
// - we want to gracefully drain ASP.NET core for requests, leaving some time for active requests to complete
// This leaves us with the following sequence of events
// - container receives SIGTERM
// - `AppHostLifetime` intercepts SIGTERM and delays for `shutdownDelay`
// - `AppHostLifetime` calls `IHostApplicationLifetime.StopApplication`, to start ASP.NET Core shutdown process
// - ASP.NET Core will spend a maximum of `shutdownTimeout` trying to drain active requests
// (cancelable requests can combine cancellation tokens with `IHostApplicationLifetime.ApplicationStopping`)
// - If ASP.NET Core completes shutdown within `shutdownTimeout`, everything is fine
// - If ASP.NET Core is stuck or in some way can't terminate, kubelet will eventually SIGKILL
- var shutdownDelay = TimeSpan.FromSeconds(5);
- var shutdownTimeout = TimeSpan.FromSeconds(20);
+ var shutdownDelay = TimeSpan.FromSeconds(
+ services.BuildServiceProvider().GetRequiredService<IConfiguration>()
+ .GetValue("GracefulShutdown:DelaySeconds", 5)
+ );
+ var shutdownTimeout = TimeSpan.FromSeconds(
+ services.BuildServiceProvider().GetRequiredService<IConfiguration>()
+ .GetValue("GracefulShutdown:TimeoutSeconds", 20)
+ );
- services.AddSingleton<IHostLifetime>(serviceProvider =>
- {
- var logger = serviceProvider.GetRequiredService<ILogger<AppHostLifetime>>();
- var env = serviceProvider.GetRequiredService<IHostEnvironment>();
- var lifetime = serviceProvider.GetRequiredService<IHostApplicationLifetime>();
- return new AppHostLifetime(logger, env, lifetime, shutdownDelay);
- });
+ // Only wire up in staging++ (tt02) and Production to avoid replacing ConsoleLifetime in Development/test-like envs
+ if (IsStagingPlus(env))
+ {
+ services.AddSingleton<IHostLifetime>(serviceProvider =>
+ {
+ var logger = serviceProvider.GetRequiredService<ILogger<AppHostLifetime>>();
+ var lifetime = serviceProvider.GetRequiredService<IHostApplicationLifetime>();
+ return new AppHostLifetime(logger, env, lifetime, shutdownDelay);
+ });
+ }
services.Configure<HostOptions>(options => options.ShutdownTimeout = shutdownTimeout);
}
+
+ private static bool IsStagingPlus(IHostEnvironment env) =>
+ env.IsProduction() || string.Equals(env.EnvironmentName, "tt02", StringComparison.OrdinalIgnoreCase);
|
||
| } | ||
49 changes: 49 additions & 0 deletions
49
src/Altinn.App.Api/Infrastructure/Lifetime/AppHostLifetime.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| using System.Runtime.InteropServices; | ||
|
|
||
| namespace Altinn.App.Api.Infrastructure.Lifetime; | ||
|
|
||
| // Based on guidance in: | ||
| // https://github.com/dotnet/dotnet-docker/blob/2a6f35b9361d1aacb664b0ce09e529698b622d2b/samples/kubernetes/graceful-shutdown/graceful-shutdown.md | ||
| internal sealed class AppHostLifetime( | ||
| ILogger<AppHostLifetime> _logger, | ||
| IHostEnvironment _environment, | ||
| IHostApplicationLifetime _applicationLifetime, | ||
| TimeSpan _delay | ||
| ) : IHostLifetime, IDisposable | ||
| { | ||
| private IEnumerable<IDisposable>? _disposables; | ||
|
|
||
| public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; | ||
|
|
||
| public Task WaitForStartAsync(CancellationToken cancellationToken) | ||
| { | ||
| if (!_environment.IsDevelopment()) | ||
| { | ||
| _disposables = | ||
| [ | ||
| PosixSignalRegistration.Create(PosixSignal.SIGINT, HandleSignal), | ||
|
||
| PosixSignalRegistration.Create(PosixSignal.SIGQUIT, HandleSignal), | ||
|
||
| PosixSignalRegistration.Create(PosixSignal.SIGTERM, HandleSignal), | ||
|
||
| ]; | ||
| } | ||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| private void HandleSignal(PosixSignalContext ctx) | ||
| { | ||
| _logger.LogInformation("Received shutdown signal: {Signal}, delaying shutdown", ctx.Signal); | ||
| ctx.Cancel = true; // Signal intercepted here, we are now responsible for calling `StopApplication` | ||
| Task.Delay(_delay) | ||
| .ContinueWith(t => | ||
| { | ||
| _logger.LogInformation("Starting host shutdown..."); | ||
| _applicationLifetime.StopApplication(); | ||
| }); | ||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| foreach (var disposable in _disposables ?? []) | ||
| disposable.Dispose(); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do not override ConsoleLifetime in Development; gate registration to tt02/prod
Registering a custom IHostLifetime unconditionally replaces ConsoleLifetime, which can break Ctrl+C handling locally. Limit registration to staging++ (tt02) and prod, and pass env to the helper.
Apply:
And update the helper signature and gating (see diff on the method below).
🤖 Prompt for AI Agents