/
monitor.go
82 lines (65 loc) · 1.38 KB
/
monitor.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
package orca
import (
"fmt"
"os"
"os/signal"
"sync"
"time"
"github.com/valyala/fasthttp"
)
var (
locker sync.RWMutex
statusCode = 503
)
func Healthy(status int) {
locker.Lock()
defer locker.Unlock()
statusCode = status
}
func healthyCheck() int {
locker.RLock()
defer locker.RUnlock()
return statusCode
}
func Monitor(conf *KeepaliveConfig, server *Server) <-chan struct{} {
s := conf.GetSignal()
c := make(chan os.Signal, len(s))
done := make(chan struct{})
signal.Notify(c, s...)
go func() {
interval := conf.GetInterval()
<-c
fmt.Println("terminate...")
Healthy(conf.GetUnhealthy())
fmt.Printf("change alive status(%d)\n", healthyCheck())
time.Sleep(interval)
err := server.Shutdown()
if nil != err {
fmt.Println("stop fatal")
} else {
fmt.Println("graceful stop...")
}
done <- struct{}{}
}()
go func() {
err := KeepaliveServer(*conf)
fmt.Printf("keepalive server err:%s\n", err)
}()
go func() {
time.Sleep(conf.GetInterval())
Healthy(conf.GetHealthy())
}()
return done
}
func KeepaliveServer(conf KeepaliveConfig) error {
return fasthttp.ListenAndServe(conf.GetAddr(), func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case conf.GetPath():
ctx.SetStatusCode(healthyCheck())
_, _ = ctx.WriteString(conf.GetMsg())
return
default:
ctx.Error("Forbidden Request", fasthttp.StatusForbidden)
}
})
}