This repository has been archived by the owner on Mar 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathsignal.go
67 lines (57 loc) · 1.44 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
package well
import (
"errors"
"os"
"os/signal"
"strconv"
"time"
"github.com/cybozu-go/log"
)
var (
errSignaled = errors.New("signaled")
cancellationDelaySecondsEnv = "CANCELLATION_DELAY_SECONDS"
defaultCancellationDelaySeconds = 5
)
// IsSignaled returns true if err returned by Wait indicates that
// the program has received SIGINT or SIGTERM.
func IsSignaled(err error) bool {
return err == errSignaled
}
// handleSignal runs independent goroutine to cancel an environment.
func handleSignal(env *Environment) {
ch := make(chan os.Signal, 2)
signal.Notify(ch, stopSignals...)
go func() {
s := <-ch
delay := getDelaySecondsFromEnv()
log.Warn("well: got signal", map[string]interface{}{
"signal": s.String(),
"delay": delay,
})
time.Sleep(time.Duration(delay) * time.Second)
env.Cancel(errSignaled)
}()
}
func getDelaySecondsFromEnv() int {
delayStr := os.Getenv(cancellationDelaySecondsEnv)
if len(delayStr) == 0 {
return defaultCancellationDelaySeconds
}
delay, err := strconv.Atoi(delayStr)
if err != nil {
log.Warn("well: set default cancellation delay seconds", map[string]interface{}{
"env": delayStr,
"delay": defaultCancellationDelaySeconds,
log.FnError: err,
})
return defaultCancellationDelaySeconds
}
if delay < 0 {
log.Warn("well: round up negative cancellation delay seconds to 0s", map[string]interface{}{
"env": delayStr,
"delay": 0,
})
return 0
}
return delay
}