10
// TrapSignals create signal handlers for all applicable signals for this
11
// system. If your Go program uses signals, this is a rather invasive
12
// function; best to implement them yourself in that case. Signals are not
13
// required for the caddy package to function properly, but this is a
14
// convenient way to allow the user to control this part of your program.
16
trapSignalsCrossPlatform()
20
// trapSignalsCrossPlatform captures SIGINT, which triggers forceful
21
// shutdown that executes shutdown callbacks first. A second interrupt
22
// signal will exit the process immediately.
23
func trapSignalsCrossPlatform() {
25
shutdown := make(chan os.Signal, 1)
26
signal.Notify(shutdown, os.Interrupt)
28
for i := 0; true; i++ {
32
log.Println("[INFO] SIGINT: Force quit")
39
log.Println("[INFO] SIGINT: Shutting down")
45
go os.Exit(executeShutdownCallbacks("SIGINT"))
50
// executeShutdownCallbacks executes the shutdown callbacks as initiated
51
// by signame. It logs any errors and returns the recommended exit status.
52
// This function is idempotent; subsequent invocations always return 0.
53
func executeShutdownCallbacks(signame string) (exitCode int) {
54
shutdownCallbacksOnce.Do(func() {
55
errs := allShutdownCallbacks()
57
for _, err := range errs {
58
log.Printf("[ERROR] %s shutdown: %v", signame, err)
66
// allShutdownCallbacks executes all the shutdown callbacks
67
// for all the instances, and returns all the errors generated
68
// during their execution. An error executing one shutdown
69
// callback does not stop execution of others. Only one shutdown
70
// callback is executed at a time.
71
func allShutdownCallbacks() []error {
74
for _, inst := range instances {
75
errs = append(errs, inst.ShutdownCallbacks()...)
81
// shutdownCallbacksOnce ensures that shutdown callbacks
82
// for all instances are only executed once.
83
var shutdownCallbacksOnce sync.Once