forked from linkerd/linkerd2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
admin.go
78 lines (65 loc) · 1.37 KB
/
admin.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
package admin
import (
"net/http"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
)
type handler struct {
promHandler http.Handler
ready bool
sync.RWMutex
}
func StartServer(addr string, readyCh <-chan struct{}) {
log.Infof("starting admin server on %s", addr)
h := &handler{
promHandler: promhttp.Handler(),
ready: readyCh == nil,
}
if readyCh != nil {
go func() {
<-readyCh
h.setReady(true)
}()
}
s := &http.Server{
Addr: addr,
Handler: h,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
log.Fatal(s.ListenAndServe())
}
func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
switch req.URL.Path {
case "/metrics":
h.promHandler.ServeHTTP(w, req)
case "/ping":
h.servePing(w, req)
case "/ready":
h.serveReady(w, req)
default:
http.NotFound(w, req)
}
}
func (h *handler) servePing(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("pong\n"))
}
func (h *handler) serveReady(w http.ResponseWriter, req *http.Request) {
if h.getReady() {
w.Write([]byte("ok\n"))
} else {
http.Error(w, "unready", http.StatusServiceUnavailable)
}
}
func (h *handler) getReady() bool {
h.RLock()
defer h.RUnlock()
return h.ready
}
func (h *handler) setReady(ready bool) {
h.Lock()
defer h.Unlock()
h.ready = ready
}