This repository has been archived by the owner on Mar 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
status.go
504 lines (423 loc) · 12.3 KB
/
status.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"sort"
"strings"
"time"
)
var statusTemplate *template.Template
var templateFns = template.FuncMap{
"marshal": func(v status) template.JS {
a, _ := json.Marshal(v)
return template.JS(a)
},
"castToFloat32": func(v int) float32 {
return float32(v)
},
"isListView": func(s status) bool {
return len(s.DBs) > 1
},
"replicationKeys": func(v versionStatus) string {
maxKey := 0
for k := range v.ReplicationHistogram {
if k > maxKey {
maxKey = k
}
}
keys := make([]string, maxKey+1, maxKey+1)
for i := 0; i <= maxKey; i++ {
keys[i] = fmt.Sprintf("%dx", maxKey-i)
}
return strings.Join(keys, "/")
},
"replicationValues": func(v versionStatus) string {
maxKey := 0
for k := range v.ReplicationHistogram {
if k > maxKey {
maxKey = k
}
}
values := make([]string, maxKey+1, maxKey+1)
for i := 0; i <= maxKey; i++ {
value := v.ReplicationHistogram[maxKey-i]
values[i] = fmt.Sprintf("%v", value)
}
return strings.Join(values, "/")
},
}
func init() {
// This is chunked into the binary with go-bindata. See the Makefile for more
// information.
raw := string(MustAsset("status.tmpl"))
statusTemplate = template.Must(template.New("status").Funcs(templateFns).Parse(raw))
}
type status struct {
DBs map[string]dbStatus `json:"dbs"`
ShardID string `json:"shard_id"`
}
type dbStatus struct {
Versions map[string]versionStatus `json:"versions"`
}
type versionStatus struct {
Path string `json:"path"`
NumPartitions int `json:"num_partitions"`
TargetReplication int `json:"target_replication"`
// Values that are recalculated with calculateReplicationStats
ReplicationHistogram map[int]int `json:"replication_histogram"`
AverageReplication float32 `json:"average_replication"`
// For backwards compatibility
MissingPartitions int `json:"missing_partitions"`
UnderreplicatedPartitions int `json:"underreplicated_partitions"`
OverreplicatedPartitions int `json:"overreplicated_partitions"`
Nodes map[string]nodeVersionStatus `json:"nodes"`
}
type nodeVersionStatus struct {
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
ActiveAt time.Time `json:"active_at,omitempty"`
Current bool `json:"current"`
State versionState `json:"state"`
Partitions []int `json:"partitions"`
ShardID string `json:"shard_id"`
}
type versionState string
const (
versionActive versionState = "ACTIVE"
versionRemoving = "REMOVING"
versionBuilding = "BUILDING"
versionError = "ERROR"
)
func (s *sequins) serveHealth(w http.ResponseWriter, r *http.Request) {
s.dbsLock.RLock()
status := status{DBs: make(map[string]dbStatus)}
for name, db := range s.dbs {
status.DBs[name] = copyDBStatus(db.status())
}
s.dbsLock.RUnlock()
if s.config.Sharding.Enabled {
w.Header().Set("X-Sequins-Shard-ID", s.peers.ShardID)
}
hostname := "localhost"
if s.peers != nil {
hostname = s.address
}
// Create a mapping of db -> version -> versionStatus for this node only
statuses := make(map[string]map[string]nodeVersionStatus)
for dbName, db := range status.DBs {
for versionName, version := range db.Versions {
if _, ok := statuses[dbName]; !ok {
statuses[dbName] = make(map[string]nodeVersionStatus)
}
statuses[dbName][versionName] = version.Nodes[hostname]
}
}
// We return a 200 when any database has an ACTIVE or BUILDING version
versionsAvailable := false
for _, db := range statuses {
for _, version := range db {
if version.State == versionActive || version.State == versionBuilding {
versionsAvailable = true
break
}
}
if versionsAvailable {
break
}
}
jsonBytes, err := json.Marshal(statuses)
if err != nil {
log.Printf("Error encoding response to JSON: %v", jsonBytes)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if versionsAvailable {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusNotFound)
}
w.Write(jsonBytes)
}
func (s *sequins) serveStatus(w http.ResponseWriter, r *http.Request) {
s.dbsLock.RLock()
status := status{DBs: make(map[string]dbStatus)}
for name, db := range s.dbs {
status.DBs[name] = copyDBStatus(db.status())
}
s.dbsLock.RUnlock()
// By default, serve our peers' statuses merged with ours. We take
// extra care not to mutate local status structs.
if r.URL.Query().Get("proxy") == "" && s.peers != nil {
for _, p := range s.peers.GetAddresses() {
peerStatus, err := s.getPeerStatus(p, "")
if err != nil {
log.Printf("Error fetching status from peer %s: %s", p, err)
continue
}
merged := peerStatus
for db := range status.DBs {
if _, ok := merged.DBs[db]; ok {
merged.DBs[db] = mergeDBStatus(merged.DBs[db], status.DBs[db])
} else {
merged.DBs[db] = status.DBs[db]
}
}
status = merged
}
for _, db := range status.DBs {
for versionName := range db.Versions {
vst := db.Versions[versionName]
vst.calculateReplicationStats()
db.Versions[versionName] = vst
}
}
}
if s.config.Sharding.Enabled {
status.ShardID = s.peers.ShardID
}
if acceptsJSON(r) {
jsonBytes, err := json.Marshal(status)
if err != nil {
log.Println("Error serving status:", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header()["Content-Type"] = []string{"application/json"}
w.Write(jsonBytes)
} else {
err := statusTemplate.Execute(w, status)
if err != nil {
log.Println("Error rendering status:", err)
}
}
}
func (db *db) serveStatus(w http.ResponseWriter, r *http.Request) {
s := db.status()
// By default, serve our peers' statuses merged with ours.
if r.URL.Query().Get("proxy") == "" && db.sequins.peers != nil {
for _, p := range db.sequins.peers.GetAddresses() {
peerStatus, err := db.sequins.getPeerStatus(p, db.name)
if err != nil {
log.Printf("Error fetching status from peer %s: %s", p, err)
continue
}
peerDBStatus := peerStatus.DBs[db.name]
s = mergeDBStatus(peerDBStatus, s)
}
for versionName := range s.Versions {
vst := s.Versions[versionName]
vst.calculateReplicationStats()
s.Versions[versionName] = vst
}
}
if acceptsJSON(r) {
jsonBytes, err := json.Marshal(s)
if err != nil {
log.Println("Error serving status:", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header()["Content-Type"] = []string{"application/json"}
w.Write(jsonBytes)
} else {
status := status{DBs: make(map[string]dbStatus)}
status.DBs[db.name] = s
err := statusTemplate.Execute(w, status)
if err != nil {
log.Println("Error rendering status:", err)
}
}
}
// getPeerStatus fetches a peer's status for the given db. If db is empty, it
// returns the status for all dbs.
func (s *sequins) getPeerStatus(peer string, db string) (status, error) {
url := fmt.Sprintf("http://%s/%s?proxy=status", peer, db)
if !strings.HasSuffix(url, "/") {
url += "/"
}
status := status{}
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Accept", "application/json")
if err != nil {
return status, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return status, err
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
if db == "" {
err = decoder.Decode(&status)
} else {
s := dbStatus{Versions: make(map[string]versionStatus)}
err = decoder.Decode(&s)
if err != nil {
return status, err
}
status.DBs = map[string]dbStatus{db: s}
}
return status, err
}
// mergeDBStatus merges two dbStatus objects, mutating only the
// left one.
func mergeDBStatus(left, right dbStatus) dbStatus {
for v, vst := range right.Versions {
if _, ok := left.Versions[v]; !ok {
left.Versions[v] = versionStatus{
Nodes: make(map[string]nodeVersionStatus),
ReplicationHistogram: vst.ReplicationHistogram,
Path: vst.Path,
NumPartitions: vst.NumPartitions,
TargetReplication: vst.TargetReplication,
}
}
for hostname, node := range right.Versions[v].Nodes {
left.Versions[v].Nodes[hostname] = node
}
}
return left
}
// copyDBStatus does a deep copy of a dbStatus object and returns it.
func copyDBStatus(status dbStatus) dbStatus {
fresh := dbStatus{Versions: make(map[string]versionStatus)}
return mergeDBStatus(fresh, status)
}
func acceptsJSON(r *http.Request) bool {
for _, accept := range r.Header["Accept"] {
if accept == "application/json" {
return true
}
}
return false
}
func (db *db) status() dbStatus {
status := dbStatus{Versions: make(map[string]versionStatus)}
for _, vs := range db.mux.getAll() {
status.Versions[vs.name] = vs.status()
}
hostname := "localhost"
if db.sequins.peers != nil {
hostname = db.sequins.address
}
current := db.mux.getCurrent()
db.mux.release(current)
for name := range status.Versions {
st := status.Versions[name].Nodes[hostname]
st.Current = (current != nil && name == current.name)
status.Versions[name].Nodes[hostname] = st
}
return status
}
func (vs *version) status() versionStatus {
vs.stateLock.Lock()
defer vs.stateLock.Unlock()
st := versionStatus{
Nodes: make(map[string]nodeVersionStatus),
NumPartitions: vs.numPartitions,
Path: vs.sequins.backend.DisplayPath(vs.db.name, vs.name),
ReplicationHistogram: make(map[int]int),
TargetReplication: vs.sequins.config.Sharding.Replication,
}
partitions := make([]int, 0, len(vs.partitions.SelectedLocal()))
for p := range vs.partitions.SelectedLocal() {
partitions = append(partitions, p)
}
hostname := "localhost"
shardID := ""
if vs.sequins.peers != nil {
hostname = vs.sequins.address
shardID = vs.sequins.peers.ShardID
}
sort.Ints(partitions)
nodeStatus := nodeVersionStatus{
Name: hostname,
CreatedAt: vs.created.UTC().Truncate(time.Second),
State: vs.state,
Partitions: partitions,
ShardID: shardID,
}
if !vs.active.IsZero() {
nodeStatus.ActiveAt = vs.active.UTC().Truncate(time.Second)
}
st.Nodes[hostname] = nodeStatus
st.calculateReplicationStats()
return st
}
func (vs *version) setState(state versionState) {
vs.stateLock.Lock()
defer vs.stateLock.Unlock()
if vs.state != versionError {
vs.state = state
if state == versionActive {
vs.active = time.Now()
if vs.stats != nil {
tags := []string{fmt.Sprintf("sequins_db:%s", vs.db.name)}
duration := vs.active.Sub(vs.created)
vs.stats.Timing("db_creation_time", duration, tags, 1)
}
}
}
}
type nodeVersionStatuses []nodeVersionStatus
func (nvs nodeVersionStatuses) Len() int {
return len(nvs)
}
func (nvs nodeVersionStatuses) Swap(i, j int) {
nvs[i], nvs[j] = nvs[j], nvs[i]
}
func (nvs nodeVersionStatuses) Less(i, j int) bool {
if cmp := strings.Compare(nvs[i].ShardID, nvs[j].ShardID); cmp != 0 {
return cmp < 0
}
return strings.Compare(nvs[i].Name, nvs[j].Name) < 0
}
// calculateReplicationStats will populate the versionStatus with replication
// information based on all of the nodes it contains. This should only be
// called once for a given versionStatus.
func (vs *versionStatus) calculateReplicationStats() {
// Reset the initial values
vs.ReplicationHistogram = make(map[int]int)
vs.MissingPartitions = 0
vs.UnderreplicatedPartitions = 0
vs.OverreplicatedPartitions = 0
partitionReplication := make(map[int]int)
for _, node := range vs.Nodes {
if node.State == versionBuilding || node.State == versionActive || node.State == versionRemoving {
for _, p := range node.Partitions {
partitionReplication[p]++
}
}
}
totalReplication := 0
for _, replication := range partitionReplication {
vs.ReplicationHistogram[replication]++
totalReplication += replication
}
if vs.NumPartitions == 0 {
vs.AverageReplication = 0
} else {
vs.AverageReplication = float32(totalReplication) / float32(vs.NumPartitions)
}
for replication, count := range vs.ReplicationHistogram {
if replication == 0 {
vs.MissingPartitions += count
} else if replication < vs.TargetReplication {
vs.UnderreplicatedPartitions += count
} else if replication > vs.TargetReplication {
vs.OverreplicatedPartitions += count
}
}
}
func (vs versionStatus) SortedNodes() nodeVersionStatuses {
nvs := make(nodeVersionStatuses, 0, len(vs.Nodes))
for _, n := range vs.Nodes {
nvs = append(nvs, n)
}
sort.Sort(nvs)
return nvs
}