-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
80 lines (60 loc) · 1.45 KB
/
watcher.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
package supervisor
import (
"os"
"os/signal"
"sync/atomic"
"github.com/toastate/toastainer/internal/config"
"github.com/toastate/toastainer/internal/runner"
"github.com/toastate/toastainer/internal/utils"
)
type Watcher struct {
shuttingdown uint32 // set to 1 atomically when shutdown is triggered
shuttingdownEvent chan bool // closed when shutdown is triggered
shutdownDone chan bool
sigchan chan os.Signal
srv *httpservers
}
func startWatcher(srv *httpservers) *Watcher {
wat := &Watcher{
srv: srv,
}
wat.shuttingdownEvent = make(chan bool)
wat.shutdownDone = make(chan bool)
wat.sigchan = make(chan os.Signal, 1)
signal.Notify(wat.sigchan, os.Interrupt)
if config.IsAPI && wat.srv != nil {
go wat.httpWatcher()
}
go wat.signalWatcher()
return wat
}
func (wat *Watcher) WaitForShutdown() {
<-wat.shutdownDone
}
func (wat *Watcher) Shutdown() {
if atomic.CompareAndSwapUint32(&wat.shuttingdown, 0, 1) {
utils.Info("msg", "Toastainer is shutting down..")
close(wat.shuttingdownEvent)
if wat.srv != nil {
wat.srv.Close()
}
if config.IsRunner {
runner.Stop()
}
close(wat.shutdownDone)
}
}
func (wat *Watcher) BlockUntilShutdownDone() {
<-wat.shutdownDone
}
func (wat *Watcher) httpWatcher() {
err := <-wat.srv.errs
if err != nil && atomic.LoadUint32(&wat.shuttingdown) == 0 {
utils.Error("msg", "API Server", err)
}
wat.Shutdown()
}
func (wat *Watcher) signalWatcher() {
<-wat.sigchan
wat.Shutdown()
}