-
Notifications
You must be signed in to change notification settings - Fork 0
/
lifecycle.go
84 lines (70 loc) · 1.75 KB
/
lifecycle.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
// Package butler is a go-framework for writing cloud/kubernetes-friendly microservices
package butler
import (
"context"
"os"
"os/signal"
"syscall"
"time"
"github.com/ninlil/butler/log"
"github.com/ninlil/butler/router"
"github.com/ninlil/butler/runtime"
"github.com/ninlil/butler/workers"
)
// Cleanup should be called using 'defer butler.Cleanup(myFunc|nil)' in your main package
func Cleanup(h func(ctx context.Context)) {
runtime.OnClose("butler_close", butlerClose)
if h != nil {
h(context.Background())
}
}
var (
sigs = make(chan os.Signal, 1)
done = make(chan bool, 1)
)
// Quit sends a signal to the butler to stop
func Quit() {
sigs <- syscall.SIGQUIT
}
func butlerClose() {
log.Trace().Msg("closing butler...")
select {
case done <- true:
//log.Trace().Msg("butler closed - ok")
case <-time.After(10 * time.Second):
log.Trace().Msg("butler close - timeout")
}
}
// Run makes the butler start all pending tasks and wait until done or signalled to stop
//
// Normal stop-signals is SIGINT and SIGTERM allowing for a graceful close/shutdown
func Run() {
runtime.OnClose("butler_close", butlerClose)
if workers.OnDone == workers.ReadyOnDone {
router.Ready = false
}
workersDone := workers.StartPending()
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
log.Info().Msgf("!! Signal = %s", sig)
runtime.Close()
done <- true
}()
if workersDone != nil {
go func() {
onDone := <-workersDone
switch onDone {
case workers.ExitOnDone:
sigs <- syscall.SIGQUIT
case workers.ContinueOnDone:
// nothing to do
case workers.ReadyOnDone:
router.Ready = true
}
}()
}
log.Trace().Msg("butler: lifecycle running (awaiting signal)")
<-done
log.Trace().Msg("butler: exiting")
}