logSignalNotifyContext is like signal.NotifyContext but logs the received signal before canceling the context.
(parent context.Context, logger slog.Logger, signals ...os.Signal)
| 626 | // logSignalNotifyContext is like signal.NotifyContext but logs the received |
| 627 | // signal before canceling the context. |
| 628 | func logSignalNotifyContext(parent context.Context, logger slog.Logger, signals ...os.Signal) (context.Context, context.CancelFunc) { |
| 629 | ctx, cancel := context.WithCancelCause(parent) |
| 630 | c := make(chan os.Signal, 1) |
| 631 | signal.Notify(c, signals...) |
| 632 | |
| 633 | go func() { |
| 634 | select { |
| 635 | case sig := <-c: |
| 636 | logger.Info(ctx, "agent received signal", slog.F("signal", sig.String())) |
| 637 | cancel(xerrors.Errorf("signal: %s", sig.String())) |
| 638 | case <-ctx.Done(): |
| 639 | logger.Info(ctx, "ctx canceled, stopping signal handler") |
| 640 | } |
| 641 | }() |
| 642 | |
| 643 | return ctx, func() { |
| 644 | cancel(context.Canceled) |
| 645 | signal.Stop(c) |
| 646 | } |
| 647 | } |