natemcmaster/CommandLineUtils

[Question] Termination Handling

Simonl9l opened this issue · 3 comments

Per the documentation,
and comment here To confirm that I should simply be able to add a CancelationToken to my Command's OnExeceuteAsync method, and then Register an Callback where I can manage termination for my specific use case's dependencies?

protected async Task<int> OnExecute(CommandLineApplication app, CancellationToken token)
{
    token.Register(CancellationCallback);
    // Do stuff for Cmd implementation...        

}

private void CancellationCallback()
{
   // Handle shutdown here - initiate shutdown processing and some kind of Task.WhenAll impl to capture each complete is shut down.
}

If I run and send a SIGTERM (pkill -SIGTERM <my process name>) the callback does not fire.

this is my main:

 public static async Task<int> Main(string[] args)
            => await CommandLineApplication.ExecuteAsync<Program>(args);

Is this correct? What an I miss interpreting here?
Thanks

In revision of above, the current implementation does not seem to support SIGTERM that is rhetorically a defecto standard when deploying processes in many environments (Docker, Kubernetes etc. - when using say a CLI as a runner...) to initiate a shutdown process.

On investigation of the code, specially the implementation of CommandLineApplication:ExecuteAsync the code essentially just hooks the Console.Cancel Key press and canceling the CancelationToken.

However my understanding as implemented:

  1. It's not "canceling" the the default shutdown process before it cancels the token in a similar way to what if does in the CommandLineLifetime implementation. It seems the:
void cancelHandler(object o, ConsoleCancelEventArgs e)
{
    e.Cancel = true ; // <--- Missing!!!
    handlerCancellationTokenSource.Cancel();
}

As annotated above (Missing!!!), as such the regular system process cancellation pulls the rug out from any graceful shutdown!

  1. It only ties directly into the console Ctrl-C process than hooking into the underline process signals al la SIGINT (Ctrl-C), SIGTERM etc. per PosixSignalRegistration (apparently the current preferred multi platform approach) as document here
    Whilst I can have my own PosixSignalRegistration register a SIGTERM handler and assign it to the same registered cancellation call back, the SIGINT (via the console Ctrl-C handler) is still problematic.

Any recommendations ?

This issue has been automatically marked as stale because it has no recent activity. It will be closed if no further activity occurs. Please comment if you believe this should remain open, otherwise it will be closed in 14 days. Thank you for your contributions to this project.

Closing due to inactivity.
If you are looking at this issue in the future and think it should be reopened, please make a commented here and mention natemcmaster so he sees the notification.