/
utilities.go
77 lines (67 loc) · 1.99 KB
/
utilities.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
package frontend
import (
"encoding/json"
"net/http"
"net/http/pprof"
"sync/atomic"
"time"
"github.com/alpacahq/marketstore/v4/utils"
"github.com/alpacahq/marketstore/v4/utils/log"
)
var Queryable uint32 // treated as bool
type HeartbeatMessage struct {
Status string `json:"status"`
Version string `json:"version"`
GitHash string `json:"git_hash"`
Uptime string `json:"uptime"`
}
func NewUtilityAPIHandlers(startTime time.Time) *UtilityAPIHandlers {
return &UtilityAPIHandlers{startTime: startTime}
}
type UtilityAPIHandlers struct {
startTime time.Time
}
func (uah *UtilityAPIHandlers) Handle(url string) error {
// heartbeat
http.HandleFunc("/heartbeat", uah.heartbeat)
// profiling
http.HandleFunc("/pprof/", pprof.Index)
http.HandleFunc("/pprof/cmdline", pprof.Cmdline)
http.HandleFunc("/pprof/profile", pprof.Profile)
http.HandleFunc("/pprof/symbol", pprof.Symbol)
http.HandleFunc("/pprof/trace", pprof.Trace)
http.Handle("/pprof/heap", pprof.Handler("heap"))
http.Handle("/pprof/goroutine", pprof.Handler("goroutine"))
http.Handle("/pprof/threadcreate", pprof.Handler("threadcreate"))
http.Handle("/pprof/block", pprof.Handler("block"))
return http.ListenAndServe(url, nil)
}
func (uah *UtilityAPIHandlers) heartbeat(rw http.ResponseWriter, _ *http.Request) {
uptime := time.Since(uah.startTime).String()
queryable := atomic.LoadUint32(&Queryable)
if queryable > 0 {
// queryable
rw.WriteHeader(http.StatusOK)
err := json.NewEncoder(rw).Encode(HeartbeatMessage{
Status: "queryable",
Version: utils.Tag,
GitHash: utils.GitHash,
Uptime: uptime,
})
if err != nil {
log.Error("Failed to write heartbeat message - Error: %v", err)
}
} else {
// not queryable
rw.WriteHeader(http.StatusServiceUnavailable)
err := json.NewEncoder(rw).Encode(HeartbeatMessage{
Status: "not queryable",
Version: utils.Tag,
GitHash: utils.GitHash,
Uptime: uptime,
})
if err != nil {
log.Error("Failed to write heartbeat message - Error: %v", err)
}
}
}