sigtrap.go 3.16 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright 2015 Light Code Labs, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16 17 18 19 20
package caddy

import (
	"log"
	"os"
	"os/signal"
21
	"sync"
22

23
	"github.com/mholt/caddy/telemetry"
24 25
)

26 27 28 29
// TrapSignals create signal handlers for all applicable signals for this
// system. If your Go program uses signals, this is a rather invasive
// function; best to implement them yourself in that case. Signals are not
// required for the caddy package to function properly, but this is a
30
// convenient way to allow the user to control this part of your program.
31 32 33 34 35 36 37 38 39
func TrapSignals() {
	trapSignalsCrossPlatform()
	trapSignalsPosix()
}

// trapSignalsCrossPlatform captures SIGINT, which triggers forceful
// shutdown that executes shutdown callbacks first. A second interrupt
// signal will exit the process immediately.
func trapSignalsCrossPlatform() {
40 41
	go func() {
		shutdown := make(chan os.Signal, 1)
42
		signal.Notify(shutdown, os.Interrupt)
43

44 45
		for i := 0; true; i++ {
			<-shutdown
46

47 48
			if i > 0 {
				log.Println("[INFO] SIGINT: Force quit")
49 50
				for _, f := range OnProcessExit {
					f() // important cleanup actions only
51
				}
52
				os.Exit(2)
53 54 55
			}

			log.Println("[INFO] SIGINT: Shutting down")
56

57 58
			telemetry.AppendUnique("sigtrap", "SIGINT")
			go telemetry.StopEmitting() // not guaranteed to finish in time; that's OK (just don't block!)
59

60 61 62
			// important cleanup actions before shutdown callbacks
			for _, f := range OnProcessExit {
				f()
63 64
			}

65 66 67
			go func() {
				os.Exit(executeShutdownCallbacks("SIGINT"))
			}()
68 69 70 71 72 73 74 75 76
		}
	}()
}

// executeShutdownCallbacks executes the shutdown callbacks as initiated
// by signame. It logs any errors and returns the recommended exit status.
// This function is idempotent; subsequent invocations always return 0.
func executeShutdownCallbacks(signame string) (exitCode int) {
	shutdownCallbacksOnce.Do(func() {
77
		// execute third-party shutdown hooks
78
		EmitEvent(ShutdownEvent, signame)
79

80
		errs := allShutdownCallbacks()
81 82
		if len(errs) > 0 {
			for _, err := range errs {
83
				log.Printf("[ERROR] %s shutdown: %v", signame, err)
84
			}
85
			exitCode = 4
86
		}
87 88
	})
	return
89
}
90

91 92 93 94 95 96 97 98 99
// allShutdownCallbacks executes all the shutdown callbacks
// for all the instances, and returns all the errors generated
// during their execution. An error executing one shutdown
// callback does not stop execution of others. Only one shutdown
// callback is executed at a time.
func allShutdownCallbacks() []error {
	var errs []error
	instancesMu.Lock()
	for _, inst := range instances {
100
		errs = append(errs, inst.ShutdownCallbacks()...)
101 102 103 104 105 106 107
	}
	instancesMu.Unlock()
	return errs
}

// shutdownCallbacksOnce ensures that shutdown callbacks
// for all instances are only executed once.
108
var shutdownCallbacksOnce sync.Once