-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgracefulshutdown.go
77 lines (67 loc) · 1.69 KB
/
gracefulshutdown.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package gracefulshutdown
import (
"fmt"
"log"
"os"
"os/signal"
"sync"
"syscall"
)
var (
gracefulShutdownSignals = []os.Signal{
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT,
}
isShutdown bool
shutdownHandlers []func() error
mu sync.Mutex
shutdownChan = make(chan struct{})
)
func init() {
sigChan := make(chan os.Signal, 2)
signal.Notify(sigChan, gracefulShutdownSignals...)
go shutdownHandler(sigChan)
}
// WaitForShutdown blocks on a channel that will never be closed.
// Its purpose is to be called by main to prevent server exit while
// shutdown handler goroutines are executing.
func WaitForShutdown() {
<-shutdownChan
}
// AddShutdownHandler registers a handler to be run before shutdown.
func AddShutdownHandler(handler func() error) {
mu.Lock()
defer mu.Unlock()
shutdownHandlers = append(shutdownHandlers, handler)
}
func shutdownHandler(sigChan chan os.Signal) {
for sig := range sigChan {
fmt.Println() // Spacer to account for ^C in terminal output.
go func(sig os.Signal) {
// If we get a second kill signal, exit immediately.
mu.Lock()
if isShutdown {
log.Printf("Received second shutdown signal %q, exiting immediately.", sig)
os.Exit(1)
}
isShutdown = true
mu.Unlock()
log.Printf("Caught signal %q, running %d shutdown handlers.", sig, len(shutdownHandlers))
var wg sync.WaitGroup
for _, hook := range shutdownHandlers {
wg.Add(1)
go func(hook func() error) {
defer wg.Done()
if err := hook(); err != nil {
log.Printf("Shutdown hook failed: %v", err)
}
}(hook)
}
wg.Wait()
log.Printf("Graceful shutdown complete, exiting.")
os.Exit(0)
}(sig)
}
}