-
Notifications
You must be signed in to change notification settings - Fork 75
/
signal.go
84 lines (71 loc) · 1.85 KB
/
signal.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
78
79
80
81
82
83
84
//go:build !wasm
// +build !wasm
package util
import (
"context"
"fmt"
"io"
"os"
"os/signal"
"sync"
"syscall"
)
// IntrHandler helps set up an interrupt handler that can
// be cleanly shut down through the io.Closer interface.
type IntrHandler struct {
closing chan struct{}
wg sync.WaitGroup
}
func NewIntrHandler() *IntrHandler {
return &IntrHandler{closing: make(chan struct{})}
}
func (ih *IntrHandler) Close() error {
close(ih.closing)
ih.wg.Wait()
return nil
}
// Handle starts handling the given signals, and will call the handler
// callback function each time a signal is caught. The function is passed
// the number of times the handler has been triggered in total, as
// well as the handler itself, so that the handling logic can use the
// handler's wait group to ensure clean shutdown when Close() is called.
func (ih *IntrHandler) Handle(handler func(count int, ih *IntrHandler), sigs ...os.Signal) {
notify := make(chan os.Signal, 1)
signal.Notify(notify, sigs...)
ih.wg.Add(1)
go func() {
defer ih.wg.Done()
defer signal.Stop(notify)
count := 0
for {
select {
case <-ih.closing:
return
case s := <-notify:
fmt.Printf("InrHandler receive signal: %+v\n", s)
count++
handler(count, ih)
}
}
}()
}
func SetupInterruptHandler(ctx context.Context) (io.Closer, context.Context) {
intrh := NewIntrHandler()
ctx, cancelFunc := context.WithCancel(ctx)
handlerFunc := func(count int, ih *IntrHandler) {
switch count {
case 1:
fmt.Println("Start handle signal") // Prevent un-terminated ^C character in terminal
ih.wg.Add(1)
go func() {
defer ih.wg.Done()
cancelFunc()
}()
default:
fmt.Println("Received another interrupt before graceful shutdown, terminating...")
os.Exit(-1)
}
}
intrh.Handle(handlerFunc, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
return intrh, ctx
}