forked from RegioHelden/innovazammad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graceful.go
68 lines (57 loc) · 1.81 KB
/
graceful.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
package main
import (
"context"
"math"
"os"
"os/signal"
"syscall"
"time"
"github.com/sirupsen/logrus"
)
// DefaultSignals is the default value for GracefulShutdownOpts.Signals
var DefaultSignals = []os.Signal{syscall.SIGTERM, os.Interrupt}
// DefaultGracePeriod is the default value for GracefulShutdownOpts.Timeout
var DefaultGracePeriod = time.Duration(math.MaxInt64)
// GracefulShutdownOpts are options for GracefulShutdownContext
type GracefulShutdownOpts struct {
// Signals is a list of signals that will trigger a graceful shutdown.
Signals []os.Signal
// Timeout is the amount of time to wait between receiving a signal in Signals and exiting.
// Leaving this at 0 means waiting indefinitely.
Timeout time.Duration
}
// GracefulShutdownContext returns a context that will be cancelled upon receiving any of the os.Signals in
// GracefulShutdownOpts.Signals.
// After receiving the first signal, we wait for either a second os.Signal or a timer of duartion
// GracefulShutdownOpts.Timeout, whichever comes first, and terminate immediately.
// If GracefulShutdownOpts.Timeout is 0, we wait indefinitely.
func GracefulShutdownContext(ctx context.Context, opts GracefulShutdownOpts) context.Context {
listenSigs := opts.Signals
if listenSigs == nil {
listenSigs = DefaultSignals
}
timeout := opts.Timeout
if timeout == time.Duration(0) {
timeout = DefaultGracePeriod
}
incomingSigs := make(chan os.Signal, 1)
signal.Notify(incomingSigs, listenSigs...)
ctx, cancel := context.WithCancel(ctx)
go func() {
select {
case got := <-incomingSigs:
logrus.Infof("received %s, gracefully terminating...", got)
cancel()
case <-ctx.Done():
cancel()
return
}
select {
case <-incomingSigs:
case <-time.After(timeout):
logrus.Warn("grace period over; exiting.")
}
os.Exit(1)
}()
return ctx
}