-
Notifications
You must be signed in to change notification settings - Fork 1
/
diagapi.go
260 lines (229 loc) · 7.29 KB
/
diagapi.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package main
import (
"encoding/json"
"fmt"
"net/http"
"path"
"runtime"
"strconv"
"strings"
"sync/atomic"
"github.com/30x/changeagent/common"
"github.com/30x/changeagent/raft"
"github.com/julienschmidt/httprouter"
"github.com/mholt/binding"
)
const (
baseURI = "/diagnostics"
stackURI = baseURI + "/stack"
idURI = baseURI + "/id"
raftURI = baseURI + "/raft"
memURI = baseURI + "/memory"
cpuURI = baseURI + "/cpu"
raftStateURI = raftURI + "/state"
raftLeaderURI = raftURI + "/leader"
healthURI = "/health"
indentPrefix = ""
indentSpace = " "
)
type healthReq struct {
up string
}
func (h *healthReq) FieldMap(req *http.Request) binding.FieldMap {
return binding.FieldMap{
&h.up: binding.Field{
Form: "up",
Required: true,
},
}
}
/*
RaftState represents the state of the Raft implementation and is used to generate
a JSON response.
*/
type RaftState struct {
ID string `json:"id"`
State string `json:"state"`
Leader string `json:"leader"`
Term uint64 `json:"term"`
NodeConfig raft.NodeList `json:"nodeConfig"`
FirstIndex uint64 `json:"firstIndex"`
LastIndex uint64 `json:"lastIndex"`
AppliedIndex uint64 `json:"appliedIndex"`
CommittedIndex uint64 `json:"committedIndex"`
PeerIndices *map[string]uint64 `json:"peerIndices,omitempty"`
}
func (a *ChangeAgent) initDiagnosticAPI(prefix string) {
a.router.GET(path.Join(prefix, "/"), a.handleRootCall)
a.router.GET(prefix+baseURI, a.handleDiagRootCall)
a.router.GET(prefix+idURI, a.handleIDCall)
a.router.GET(prefix+raftStateURI, a.handleStateCall)
a.router.GET(prefix+raftLeaderURI, a.handleLeaderCall)
a.router.GET(prefix+raftURI, a.handleRaftInfo)
a.router.GET(prefix+stackURI, handleStackCall)
a.router.GET(prefix+memURI, handleMemoryCall)
a.router.GET(prefix+cpuURI, handleCPUCall)
a.router.GET(prefix+healthURI, a.handleHealthCheck)
a.router.POST(prefix+healthURI, a.handleHealthUpdate)
a.router.PUT(prefix+healthURI, a.handleHealthUpdate)
}
func (a *ChangeAgent) handleRootCall(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
links := make(map[string]string)
// TODO convert links properly
links["changes"] = a.makeLink(req, "/changes")
links["diagnostics"] = a.makeLink(req, "/diagnostics")
links["cluster"] = a.makeLink(req, "/cluster")
links["config"] = a.makeLink(req, "/config")
links["health"] = a.makeLink(req, "/health")
body, _ := json.MarshalIndent(&links, indentPrefix, indentSpace)
resp.Header().Set("Content-Type", jsonContent)
resp.Write(body)
}
func (a *ChangeAgent) handleDiagRootCall(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
o := make(map[string]string)
// TODO convert links properly
o["arch"] = runtime.GOARCH
o["os"] = runtime.GOOS
o["maxprocs"] = strconv.Itoa(runtime.GOMAXPROCS(-1))
o["id"] = a.makeLink(req, idURI)
o["stack"] = a.makeLink(req, stackURI)
o["raft"] = a.makeLink(req, raftURI)
o["memory"] = a.makeLink(req, memURI)
o["cpu"] = a.makeLink(req, cpuURI)
body, _ := json.MarshalIndent(&o, indentPrefix, indentSpace)
resp.Header().Set("Content-Type", jsonContent)
resp.Write(body)
}
func (a *ChangeAgent) handleIDCall(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
resp.Header().Set("Content-Type", plainTextContent)
resp.Write([]byte(a.raft.MyID().String()))
}
func (a *ChangeAgent) handleStateCall(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
resp.Header().Set("Content-Type", plainTextContent)
resp.Write([]byte(a.GetRaftState().String()))
}
func (a *ChangeAgent) handleLeaderCall(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
resp.Header().Set("Content-Type", plainTextContent)
resp.Write([]byte(a.getLeaderID().String()))
}
func (a *ChangeAgent) handleRaftInfo(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
status := a.raft.GetRaftStatus()
last, term := a.raft.GetLastIndex()
first, _ := a.raft.GetFirstIndex()
state := RaftState{
ID: a.raft.MyID().String(),
State: a.GetRaftState().String(),
Leader: a.getLeaderID().String(),
Term: term,
NodeConfig: a.raft.GetNodeConfig(),
FirstIndex: first,
LastIndex: last,
AppliedIndex: a.raft.GetLastApplied(),
CommittedIndex: a.raft.GetCommitIndex(),
}
pis := make(map[string]uint64)
if status.PeerIndices != nil {
for pik, piv := range *status.PeerIndices {
pis[pik.String()] = piv
}
state.PeerIndices = &pis
}
body, err := json.MarshalIndent(&state, indentPrefix, indentSpace)
if err != nil {
writeError(resp, 500, err)
return
}
resp.Header().Set("Content-Type", jsonContent)
resp.Write(body)
}
func (a *ChangeAgent) getLeaderID() common.NodeID {
if a.GetRaftState() == raft.Leader {
return a.raft.MyID()
}
return a.raft.GetLeaderID()
}
func handleStackCall(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
stackBufLen := 64
for {
stackBuf := make([]byte, stackBufLen)
stackLen := runtime.Stack(stackBuf, true)
if stackLen == len(stackBuf) {
// Must be truncated
stackBufLen *= 2
} else {
resp.Header().Set("Content-Type", plainTextContent)
resp.Write(stackBuf)
return
}
}
}
func handleMemoryCall(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
s := make(map[string]uint64)
s["alloc"] = stats.Alloc
s["totalAlloc"] = stats.TotalAlloc
s["sys"] = stats.Sys
s["lookups"] = stats.Lookups
s["mallocs"] = stats.Mallocs
s["frees"] = stats.Frees
body, _ := json.MarshalIndent(&s, indentPrefix, indentSpace)
resp.Header().Set("Content-Type", jsonContent)
resp.Write(body)
}
func handleCPUCall(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
s := make(map[string]int64)
s["gomaxprocs"] = int64(runtime.GOMAXPROCS(-1))
s["numcpu"] = int64(runtime.NumCPU())
s["numcgocall"] = runtime.NumCgoCall()
s["numgoroutine"] = int64(runtime.NumGoroutine())
body, _ := json.MarshalIndent(&s, indentPrefix, indentSpace)
resp.Header().Set("Content-Type", jsonContent)
resp.Write(body)
}
func (a *ChangeAgent) handleHealthCheck(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
resp.Header().Set("Content-Type", "text/plain")
markedDown := atomic.LoadInt32(&a.markedDown)
if markedDown == 0 {
// This will hang if the main loop is stuck somehow, so it's a good
// thing to call here.
a.raft.GetRaftStatus()
resp.Write([]byte("ok"))
} else {
resp.WriteHeader(http.StatusServiceUnavailable)
resp.Write([]byte("marked down"))
}
}
func (a *ChangeAgent) handleHealthUpdate(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
healthReq := &healthReq{}
defer req.Body.Close()
bindingErr := binding.Bind(req, healthReq)
if bindingErr.Handle(resp) {
return
}
var down int32
if !strings.EqualFold(healthReq.up, "true") {
down = 1
}
atomic.StoreInt32(&a.markedDown, down)
}
func (a *ChangeAgent) makeLink(req *http.Request, path string) string {
var proto string
if req.TLS == nil {
proto = "http"
} else {
proto = "https"
}
return fmt.Sprintf("%s://%s%s%s", proto, req.Host, a.uriPrefix, path)
}