forked from couchbase/cbft
/
ns_server.go
executable file
·361 lines (312 loc) · 9.04 KB
/
ns_server.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
// Copyright (c) 2014 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
package cbft
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"unicode"
"github.com/couchbase/cbgt"
"github.com/couchbase/cbgt/rest"
"github.com/dustin/go-jsonpointer"
)
var statsNamePrefix = []byte("\"")
var statsNameSuffix = []byte("\":")
// NsStatsHandler is a REST handler that provides stats/metrics for
// consumption by ns_server
type NsStatsHandler struct {
mgr *cbgt.Manager
}
func NewNsStatsHandler(mgr *cbgt.Manager) *NsStatsHandler {
return &NsStatsHandler{mgr: mgr}
}
type NSIndexStats map[string]map[string]interface{}
// MarshalJSON formats the index stats using the
// colon separated convention found in other
// stats consumed by ns_server
func (n NSIndexStats) MarshalJSON() ([]byte, error) {
rv := make(map[string]interface{})
for k, nsis := range n {
for nsik, nsiv := range nsis {
if k == "" {
rv[nsik] = nsiv
} else {
rv[k+":"+nsik] = nsiv
}
}
}
return json.Marshal(rv)
}
var statkeys = []string{
// manual
"num_pindexes",
// pindex
"doc_count",
"timer_batch_execute_count", "timer_batch_merge_count", "timer_batch_store_count",
"timer_iterator_next_count", "timer_iterator_seek_count", "timer_iterator_seek_first_count",
"timer_reader_get_count", "timer_reader_iterator_count", "timer_writer_delete_count",
"timer_writer_get_count", "timer_writer_iterator_count", "timer_writer_set_count",
// feed
"timer_opaque_set_count", "timer_rollback_count", "timer_data_update_count",
"timer_data_delete_count", "timer_snapshot_start_count", "timer_opaque_get_count",
}
// NewIndexStat ensures that all index stats
// have the same shape and 0 values to
// prevent seeing N/A in ns_server UI
func NewIndexStat() map[string]interface{} {
rv := make(map[string]interface{})
for _, key := range statkeys {
rv[key] = float64(0)
}
return rv
}
func (h *NsStatsHandler) ServeHTTP(
w http.ResponseWriter, req *http.Request) {
_, indexDefsMap, err := h.mgr.GetIndexDefs(false)
if err != nil {
rest.ShowError(w, req, "could not retrieve index defs", 500)
return
}
nsIndexStats := make(NSIndexStats, len(indexDefsMap))
for indexDefName, indexDef := range indexDefsMap {
nsIndexStats[indexDef.SourceName+":"+indexDefName] = NewIndexStat()
}
feeds, pindexes := h.mgr.CurrentMaps()
sourceName := ""
for _, pindex := range pindexes {
sourceName = pindex.SourceName
lindexName := pindex.SourceName + ":" + pindex.IndexName
nsIndexStat, ok := nsIndexStats[lindexName]
if ok {
// manually track a statistic representing
// the number of pindex in the index
oldValue, ok := nsIndexStat["num_pindexes"]
if ok {
switch oldValue := oldValue.(type) {
case float64:
oldValue += float64(1)
nsIndexStat["num_pindexes"] = oldValue
}
}
// automatically process all the pindex dest stats
err := addPindexStats(pindex, nsIndexStat)
if err != nil {
rest.ShowError(w, req, fmt.Sprintf("error processing PIndex stats: %v", err), 500)
return
}
}
}
for _, feed := range feeds {
lindexName := sourceName + ":" + feed.IndexName()
nsIndexStat, ok := nsIndexStats[lindexName]
if ok {
err := addFeedStats(feed, nsIndexStat)
// automatically process all the feed stats
if err != nil {
rest.ShowError(w, req, fmt.Sprintf("error processing Feed stats: %v", err), 500)
return
}
}
}
// FIXME hard-coded top-level stats
nsIndexStats[""] = make(map[string]interface{})
nsIndexStats[""]["num_connections"] = 0
nsIndexStats[""]["needs_restart"] = false
rest.MustEncode(w, nsIndexStats)
}
func addFeedStats(feed cbgt.Feed, nsIndexStat map[string]interface{}) error {
buffer := new(bytes.Buffer)
err := feed.Stats(buffer)
if err != nil {
return err
}
return massageStats(buffer, nsIndexStat)
}
func addPindexStats(pindex *cbgt.PIndex, nsIndexStat map[string]interface{}) error {
buffer := new(bytes.Buffer)
err := pindex.Dest.Stats(buffer)
if err != nil {
return err
}
return massageStats(buffer, nsIndexStat)
}
func massageStats(buffer *bytes.Buffer, nsIndexStat map[string]interface{}) error {
statsBytes := buffer.Bytes()
pointers, err := jsonpointer.ListPointers(statsBytes)
if err != nil {
return err
}
countPointers := make([]string, 0)
for _, pointer := range pointers {
if strings.HasSuffix(pointer, "/count") ||
strings.HasSuffix(pointer, "/DocCount") {
countPointers = append(countPointers, pointer)
}
}
countValueMap, err := jsonpointer.FindMany(statsBytes, countPointers)
if err != nil {
return err
}
for k, v := range countValueMap {
statName := convertStatName(k)
var statValue float64
err := json.Unmarshal(v, &statValue)
if err != nil {
return err
}
oldValue, ok := nsIndexStat[statName]
if ok {
switch oldValue := oldValue.(type) {
case float64:
oldValue += statValue
nsIndexStat[statName] = oldValue
}
}
}
return nil
}
func convertStatName(key string) string {
lastSlash := strings.LastIndex(key, "/")
if lastSlash < 0 {
return "unknown"
}
statSuffix := key[lastSlash+1:]
statNameStart := strings.LastIndex(key[:lastSlash], "/")
if statNameStart < 0 {
return "unknown"
}
statPrefix := key[statNameStart+1 : lastSlash]
if statPrefix == "basic" {
statPrefix = ""
}
statName := camelToUnderscore(statSuffix)
if statPrefix != "" {
statName = camelToUnderscore(statPrefix) + "_" + statName
}
return statName
}
func camelToUnderscore(name string) string {
rv := ""
for i, r := range name {
if unicode.IsUpper(r) && i != 0 {
rv += "_"
rv += string(unicode.ToLower(r))
} else if unicode.IsUpper(r) && i == 0 {
rv += string(unicode.ToLower(r))
} else {
rv += string(r)
}
}
return rv
}
// ---------------------------------------------------
// NsStatusHandler is a REST handler that provides status for
// consumption by ns_server
type NsStatusHandler struct {
mgr *cbgt.Manager
serverURL *url.URL
}
func NewNsStatusHandler(mgr *cbgt.Manager, server string) (*NsStatusHandler, error) {
serverURL, err := url.Parse(server)
if err != nil {
return nil, err
}
return &NsStatusHandler{
mgr: mgr,
serverURL: serverURL,
}, nil
}
func HostsForIndex(name string, planPIndexes *cbgt.PlanPIndexes, nodeDefs *cbgt.NodeDefs) []string {
// find the node UUIDs related to this index
nodes := make(map[string]struct{})
for _, planPIndex := range planPIndexes.PlanPIndexes {
if planPIndex.IndexName == name {
for planPIndexNodeUUID := range planPIndex.Nodes {
nodes[planPIndexNodeUUID] = struct{}{}
}
}
}
nodeExtras := make(map[string]string)
// look for all these nodes in the nodes wanted
for _, nodeDef := range nodeDefs.NodeDefs {
_, ok := nodes[nodeDef.UUID]
if ok {
nodeExtras[nodeDef.UUID] = nodeDef.Extras
}
}
// build slide of node extras
nodeStrings := make(sort.StringSlice, 0, len(nodeExtras))
for _, nodeExtra := range nodeExtras {
nodeStrings = append(nodeStrings, nodeExtra)
}
// sort slice for stability
sort.Sort(nodeStrings)
return nodeStrings
}
func (h *NsStatusHandler) ServeHTTP(
w http.ResponseWriter, req *http.Request) {
cfg := h.mgr.Cfg()
planPIndexes, _, err := cbgt.CfgGetPlanPIndexes(cfg)
if err != nil {
rest.ShowError(w, req, "could not retrieve plan pIndexes", 500)
return
}
nodesDefs, _, err := cbgt.CfgGetNodeDefs(cfg, cbgt.NODE_DEFS_WANTED)
if err != nil {
rest.ShowError(w, req, "could not retrieve node defs (wanted)", 500)
return
}
_, indexDefsMap, err := h.mgr.GetIndexDefs(false)
if err != nil {
rest.ShowError(w, req, "could not retrieve index defs", 500)
return
}
w.Write(cbgt.JsonOpenBrace)
w.Write(statsNamePrefix)
w.Write([]byte("status"))
w.Write(statsNameSuffix)
w.Write([]byte("["))
indexDefNames := make(sort.StringSlice, 0, len(indexDefsMap))
for indexDefName := range indexDefsMap {
indexDefNames = append(indexDefNames, indexDefName)
}
sort.Sort(indexDefNames)
for i, indexDefName := range indexDefNames {
indexDef := indexDefsMap[indexDefName]
if i > 0 {
w.Write(cbgt.JsonComma)
}
rest.MustEncode(w, struct {
Completion int `json:"completion"`
Hosts []string `json:"hosts"`
Status string `json:"status"`
Bucket string `json:"bucket"`
Name string `json:"name"`
}{
Bucket: indexDef.SourceName,
Name: indexDefName,
Hosts: HostsForIndex(indexDefName, planPIndexes, nodesDefs),
// FIXME hard-coded
Completion: 100,
Status: "Ready",
})
}
w.Write([]byte("],"))
w.Write(statsNamePrefix)
w.Write([]byte("code"))
w.Write(statsNameSuffix)
w.Write([]byte("\"success\""))
w.Write(cbgt.JsonCloseBrace)
}