-
Notifications
You must be signed in to change notification settings - Fork 9
/
graceful.go
101 lines (88 loc) · 2.12 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Copyright 2023 sigma
//
// 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.
package graceful
import (
"context"
"sort"
"sync"
"time"
"github.com/rs/zerolog/log"
)
const (
ctxNameKey = "name"
)
var (
gracefulShutdownTimeout = time.Second * 30
ctx, ctxCancel = context.WithCancel(context.Background())
runAtShutdown []item
)
type item struct {
name string
index int
f func()
}
// GetCtx ...
func GetCtx(name string) context.Context {
return context.WithValue(ctx, ctxNameKey, name) // nolint: staticcheck
}
// RunAtShutdown ...
func RunAtShutdown(name string, index int, f func()) {
if f == nil {
return
}
runAtShutdown = append(runAtShutdown, item{
name: name,
index: index,
f: f,
})
}
// Shutdown ...
func Shutdown() {
ctxCancel()
sort.SliceStable(runAtShutdown, func(i, j int) bool {
return runAtShutdown[i].index < runAtShutdown[j].index
})
gCtx, gCtxCancel := context.WithTimeout(context.Background(), gracefulShutdownTimeout)
waitGroupDone := make(chan struct{})
go func() {
for _, item := range runAtShutdown {
select {
case <-gCtx.Done():
return
default:
}
waitGroup := &sync.WaitGroup{}
waitGroup.Add(1)
go func(name string, f func()) {
defer func() {
waitGroup.Done()
err := recover()
if err != nil {
log.Error().Msgf("Panic during shutting down %s", name)
}
}()
log.Info().Str("name", name).Msg("Shutting down")
f()
}(item.name, item.f)
waitGroup.Wait()
}
waitGroupDone <- struct{}{}
}()
select {
case <-gCtx.Done():
log.Error().Msg("Timeout shutting down")
case <-waitGroupDone:
}
gCtxCancel()
}