forked from viamrobotics/goutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntime.go
184 lines (164 loc) · 5.27 KB
/
runtime.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// Package utils contains all utility functions that currently have no better home than here.
package utils
import (
"context"
"fmt"
"os"
"os/signal"
"runtime/debug"
"sync"
"syscall"
"time"
"github.com/edaniels/golog"
)
// ContextualMain calls a main entry point function with a cancellable
// context via SIGTERM. This should be called once per process so as
// to not clobber the signals from Notify.
func ContextualMain(main func(ctx context.Context, args []string, logger golog.Logger) error, logger golog.Logger) {
// This will only run on a successful exit due to the fatal error
// logic in contextualMain.
defer func() {
if err := FindGoroutineLeaks(); err != nil {
fmt.Fprintf(os.Stderr, "goroutine leak(s) detected: %v\n", err)
}
}()
contextualMain(main, false, logger)
}
// ContextualMainQuit is the same as ContextualMain but catches quit signals into the provided
// context accessed via ContextMainQuitSignal.
func ContextualMainQuit(main func(ctx context.Context, args []string, logger golog.Logger) error, logger golog.Logger) {
contextualMain(main, true, logger)
}
func contextualMain(main func(ctx context.Context, args []string, logger golog.Logger) error, quitSignal bool, logger golog.Logger) {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if quitSignal {
quitC := make(chan os.Signal, 1)
signal.Notify(quitC, syscall.SIGQUIT)
ctx = ContextWithQuitSignal(ctx, quitC)
}
readyC := make(chan struct{})
ctx = ContextWithReadyFunc(ctx, readyC)
if err := FilterOutError(main(ctx, os.Args, logger), context.Canceled); err != nil {
fatal(logger, err)
}
}
var fatal = func(logger golog.Logger, args ...interface{}) {
logger.Fatal(args...)
}
type ctxKey int
const (
ctxKeyQuitSignaler = ctxKey(iota)
ctxKeyReadyFunc
ctxKeyIterFunc
)
// ContextWithQuitSignal attaches a quit signaler to the given context.
func ContextWithQuitSignal(ctx context.Context, c <-chan os.Signal) context.Context {
return context.WithValue(ctx, ctxKeyQuitSignaler, c)
}
// ContextMainQuitSignal returns a signal channel for quits. It may
// be nil if the value was never set.
func ContextMainQuitSignal(ctx context.Context) <-chan os.Signal {
signaler := ctx.Value(ctxKeyQuitSignaler)
if signaler == nil {
return nil
}
return signaler.(<-chan os.Signal)
}
// ContextWithReadyFunc attaches a ready signaler to the given context.
func ContextWithReadyFunc(ctx context.Context, c chan<- struct{}) context.Context {
closeOnce := sync.Once{}
return context.WithValue(ctx, ctxKeyReadyFunc, func() {
closeOnce.Do(func() {
close(c)
})
})
}
// ContextMainReadyFunc returns a function for indicating readiness. This
// is intended for main functions that block forever (e.g. daemons).
func ContextMainReadyFunc(ctx context.Context) func() {
signaler := ctx.Value(ctxKeyReadyFunc)
if signaler == nil {
return func() {}
}
return signaler.(func())
}
// ContextWithIterFunc attaches an iteration func to the given context.
func ContextWithIterFunc(ctx context.Context, f func()) context.Context {
return context.WithValue(ctx, ctxKeyIterFunc, f)
}
// ContextMainIterFunc returns a function for indicating an iteration of the
// program has completed.
func ContextMainIterFunc(ctx context.Context) func() {
iterFunc := ctx.Value(ctxKeyIterFunc)
if iterFunc == nil {
return func() {}
}
return iterFunc.(func())
}
// PanicCapturingGo spawns a goroutine to run the given function and captures
// any panic that occurs and logs it.
func PanicCapturingGo(f func()) {
PanicCapturingGoWithCallback(f, nil)
}
const waitDur = 3 * time.Second
// PanicCapturingGoWithCallback spawns a goroutine to run the given function and captures
// any panic that occurs, logs it, and calls the given callback. The callback can be
// used for restart functionality.
func PanicCapturingGoWithCallback(f func(), callback func(err interface{})) {
go func() {
defer func() {
if err := recover(); err != nil {
debug.PrintStack()
golog.Global().Errorw("panic while running function", "error", err)
if callback == nil {
return
}
golog.Global().Infow("waiting a bit to call callback", "wait", waitDur.String())
time.Sleep(waitDur)
callback(err)
}
}()
f()
}()
}
// ManagedGo keeps the given function alive in the background until
// it terminates normally.
func ManagedGo(f, onComplete func()) {
PanicCapturingGoWithCallback(func() {
defer func() {
if err := recover(); err == nil && onComplete != nil {
onComplete()
} else if err != nil {
// re-panic
panic(err)
}
}()
f()
}, func(_ interface{}) {
ManagedGo(f, onComplete)
})
}
// SelectContextOrWait either terminates because the given context is done
// or the given duration elapses. It returns true if the duration elapsed.
func SelectContextOrWait(ctx context.Context, dur time.Duration) bool {
timer := time.NewTimer(dur)
defer timer.Stop()
return SelectContextOrWaitChan(ctx, timer.C)
}
// SelectContextOrWaitChan either terminates because the given context is done
// or the given time channel is received on. It returns true if the channel
// was received on.
func SelectContextOrWaitChan(ctx context.Context, c <-chan time.Time) bool {
select {
case <-ctx.Done():
return false
default:
}
select {
case <-ctx.Done():
return false
case <-c:
}
return true
}