-
Notifications
You must be signed in to change notification settings - Fork 12
/
misc.go
527 lines (475 loc) · 13.3 KB
/
misc.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// Copyright 2014-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package cbgt
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math"
"math/rand"
"net/http"
"os"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"sync/atomic"
"time"
log "github.com/couchbase/clog"
"github.com/rcrowley/go-metrics"
)
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
// DiagHandler allows modules to provide their own additions in
// response to "diag" or diagnostic information requests.
type DiagHandler struct {
Name string
Handler http.Handler
HandlerFunc http.HandlerFunc
}
// Documentation is used for auto-generated documentation.
type Documentation struct {
Text string // Optional documentation text (markdown).
JSON interface{} // Optional marshall'able to JSON.
}
var EMPTY_BYTES = []byte{}
var JsonNULL = []byte("null")
var JsonOpenBrace = []byte("{")
var JsonCloseBrace = []byte("}")
var JsonCloseBraceComma = []byte("},")
var JsonComma = []byte(",")
// IndentJSON is a helper func that returns indented JSON for its
// interface{} x parameter.
func IndentJSON(x interface{}, prefix, indent string) string {
j, err := MarshalJSON(x)
if err != nil {
return fmt.Sprintf("misc: IndentJSON marshal, err: %v", err)
}
var buf bytes.Buffer
err = json.Indent(&buf, j, prefix, indent)
if err != nil {
return fmt.Sprintf("misc: IndentJSON indent, err: %v", err)
}
return buf.String()
}
// ErrorToString is a helper func that returns e.Error(), but also
// returns "" for nil error.
func ErrorToString(e error) string {
if e != nil {
return e.Error()
}
return ""
}
// Compares two dotted versioning strings, like "1.0.1" and "1.2.3".
// Returns true when x >= y.
//
// TODO: Need to handle non-numeric parts?
func VersionGTE(x, y string) bool {
xa := strings.Split(x, ".")
ya := strings.Split(y, ".")
for i := range xa {
if i >= len(ya) {
return true
}
xv, err := strconv.Atoi(xa[i])
if err != nil {
return false
}
yv, err := strconv.Atoi(ya[i])
if err != nil {
return false
}
if xv > yv {
return true
}
if xv < yv {
return false
}
}
return len(xa) >= len(ya)
}
func NewUUID() string {
val1 := rand.Int63()
val2 := rand.Int63()
uuid := fmt.Sprintf("%x%x", val1, val2)
return uuid[0:16]
}
func encodeUUID(dst []byte, uuid []byte) {
hex.Encode(dst, uuid[:4])
dst[8] = '-'
hex.Encode(dst[9:13], uuid[4:6])
dst[13] = '-'
hex.Encode(dst[14:18], uuid[6:8])
dst[18] = '-'
hex.Encode(dst[19:23], uuid[8:10])
dst[23] = '-'
hex.Encode(dst[24:], uuid[10:])
}
func NewUUIDV4() string {
uuid := []byte(NewUUID())
uuid[6] = (uuid[6] & 0x0f) | 0x40
uuid[8] = (uuid[8] & 0x3f) | 0x80
var buf [36]byte
encodeUUID(buf[:], uuid[:])
return string(buf[:])
}
func RetryOnCASMismatch(task func() error, retrycount int) error {
var err error
tries := 0
for {
tries += 1
// A negative retry count indicates infinite retries.
if retrycount > 0 && tries > retrycount {
return NewInternalServerError("RetryOnCASMismatch: too many tries")
}
err = task()
if err != nil {
if _, ok := err.(*CfgCASError); ok {
log.Printf("misc: retrying due to cas mismatch")
continue
}
return err
}
break
}
return err
}
// Calls f() in a loop, sleeping in an exponential backoff if needed.
// The provided f() function should return < 0 to stop the loop; >= 0
// to continue the loop, where > 0 means there was progress which
// allows an immediate retry of f() with no sleeping. A return of < 0
// is useful when f() will never make any future progress.
func ExponentialBackoffLoop(name string,
f func() int,
startSleepMS int,
backoffFactor float32,
maxSleepMS int) {
nextSleepMS := startSleepMS
for {
progress := f()
if progress < 0 {
return
}
if progress > 0 {
// When there was some progress, we can reset nextSleepMS.
nextSleepMS = startSleepMS
} else {
// If zero progress was made this cycle, then sleep.
time.Sleep(time.Duration(nextSleepMS) * time.Millisecond)
// Increase nextSleepMS in case next time also has 0 progress.
nextSleepMS = int(float32(nextSleepMS) * backoffFactor)
if nextSleepMS > maxSleepMS {
nextSleepMS = maxSleepMS
}
}
}
}
// StringsToMap connverts an array of (perhaps duplicated) strings
// into a map with key of those strings and values of true, and is
// useful for simple set-like operations.
func StringsToMap(strsArr []string) map[string]bool {
if strsArr == nil {
return nil
}
strs := map[string]bool{}
for _, str := range strsArr {
strs[str] = true
}
return strs
}
// StringsRemoveDuplicates removes any duplicate strings from the give slice.
func StringsRemoveDuplicates(strsArr []string) []string {
if len(strsArr) <= 1 {
return strsArr
}
rv := make([]string, 0, len(strsArr))
lookup := make(map[string]struct{}, len(strsArr))
for _, str := range strsArr {
if _, ok := lookup[str]; !ok {
lookup[str] = struct{}{}
rv = append(rv, str)
}
}
return rv
}
// StringsRemoveStrings returns a copy of stringArr, but with some
// strings removed, keeping the same order as stringArr.
func StringsRemoveStrings(stringArr, removeArr []string) []string {
removeMap := StringsToMap(removeArr)
rv := make([]string, 0, len(stringArr))
for _, s := range stringArr {
if !removeMap[s] {
rv = append(rv, s)
}
}
return rv
}
// StringsIntersectStrings returns a brand new array that has the
// intersection of a and b.
func StringsIntersectStrings(a, b []string) []string {
bMap := StringsToMap(b)
rMap := map[string]bool{}
rv := make([]string, 0, len(a))
for _, s := range a {
if bMap[s] && !rMap[s] {
rMap[s] = true
rv = append(rv, s)
}
}
return rv
}
// TimeoutCancelChan creates a channel that closes after a given
// timeout in milliseconds.
func TimeoutCancelChan(timeout int64) <-chan bool {
if timeout > 0 {
cancelCh := make(chan bool, 1)
go func() {
time.Sleep(time.Duration(timeout) * time.Millisecond)
close(cancelCh)
}()
return cancelCh
}
return nil
}
// Time invokes a func f and updates the totalDuration, totalCount and
// maxDuration metrics. See also Timer() for a metrics based
// alternative.
func Time(f func() error,
totalDuration, totalCount, maxDuration *uint64) error {
startTime := time.Now()
err := f()
duration := uint64(time.Since(startTime))
atomic.AddUint64(totalDuration, duration)
if totalCount != nil {
atomic.AddUint64(totalCount, 1)
}
if maxDuration != nil {
retry := true
for retry {
retry = false
md := atomic.LoadUint64(maxDuration)
if md < duration {
retry = !atomic.CompareAndSwapUint64(maxDuration, md, duration)
}
}
}
return err
}
// Timer updates a metrics.Timer. Unlike metrics.Timer.Time(), this
// version also captures any error return value.
func Timer(f func() error, t metrics.Timer) error {
var err error
t.Time(func() {
err = f()
})
return err
}
// AtomicCopyMetrics copies uint64 metrics from s to r (from source to
// result), and also applies an optional fn function to each metric.
// The fn is invoked with metrics from s and r, and can be used to
// compute additions, subtractions, etc. When fn is nil, AtomicCopyTo
// defaults to just a straight copier.
func AtomicCopyMetrics(s, r interface{},
fn func(sv uint64, rv uint64) uint64) {
// Using reflection rather than a whole slew of explicit
// invocations of atomic.LoadUint64()/StoreUint64()'s.
if fn == nil {
fn = func(sv uint64, rv uint64) uint64 { return sv }
}
rve := reflect.ValueOf(r).Elem()
sve := reflect.ValueOf(s).Elem()
svet := sve.Type()
for i := 0; i < svet.NumField(); i++ {
rvef := rve.Field(i)
svef := sve.Field(i)
if rvef.CanAddr() && svef.CanAddr() {
rvefp := rvef.Addr().Interface()
svefp := svef.Addr().Interface()
rv := atomic.LoadUint64(rvefp.(*uint64))
sv := atomic.LoadUint64(svefp.(*uint64))
atomic.StoreUint64(rvefp.(*uint64), fn(sv, rv))
}
}
}
// StructChanges uses reflection to compare the fields of two structs,
// which must the same type, and returns info on the changes of field
// values.
func StructChanges(a1, a2 interface{}) (rv []string) {
if a1 == nil || a2 == nil {
return nil
}
v1 := reflect.ValueOf(a1)
v2 := reflect.ValueOf(a2)
if v1.Type() != v2.Type() {
return nil
}
if v1.Kind() != v2.Kind() ||
v1.Kind() != reflect.Struct {
return nil
}
for i := 0; i < v1.NumField(); i++ {
v1f := v1.Field(i)
v2f := v2.Field(i)
if v1f.Kind() == v2f.Kind() &&
v1f.Kind() == reflect.Int {
if v1f.Int() != v2f.Int() {
rv = append(rv, fmt.Sprintf("%s: %d -> %d",
v2.Type().Field(i).Name, v1f.Int(), v2f.Int()))
}
}
}
return rv
}
var timerPercentiles = []float64{0.5, 0.75, 0.95, 0.99, 0.999}
// WriteTimerJSON writes a metrics.Timer instance as JSON to a
// io.Writer.
func WriteTimerJSON(w io.Writer, timer metrics.Timer) {
t := timer.Snapshot()
p := t.Percentiles(timerPercentiles)
fmt.Fprintf(w, `{"count":%9d,`, t.Count())
fmt.Fprintf(w, `"min":%9d,`, t.Min())
fmt.Fprintf(w, `"max":%9d,`, t.Max())
mean := t.Mean()
if !isNanOrInf(mean) {
fmt.Fprintf(w, `"mean":%12.2f,`, mean)
}
stddev := t.StdDev()
if !isNanOrInf(stddev) {
fmt.Fprintf(w, `"stddev":%12.2f,`, stddev)
}
fPrintFloatMap(w, "percentiles", map[string]float64{
"median": p[0],
"75%": p[1],
"95%": p[2],
"99%": p[3],
"99.9%": p[4],
})
fmt.Fprintf(w, `,`)
fPrintFloatMap(w, "rates", map[string]float64{
"1-min": t.Rate1(),
"5-min": t.Rate5(),
"15-min": t.Rate15(),
"mean": t.RateMean(),
})
fmt.Fprintf(w, `}`)
}
// a helper to safely print a json map with string keys and float64 values
// if +/-Inf or NaN values are encountered, that k/v pair is omitted
// if there are no valid values in the map, the named map is still emitted
// with no contents, ie:
//
// "name":{}
func fPrintFloatMap(w io.Writer, name string, vals map[string]float64) {
fmt.Fprintf(w, `"%s":{`, name)
first := true
for k, v := range vals {
if !isNanOrInf(v) {
if !first {
fmt.Fprintf(w, `,`)
}
fmt.Fprintf(w, `"%s":%12.2f`, k, v)
first = false
}
}
fmt.Fprintf(w, `}`)
}
func isNanOrInf(v float64) bool {
if math.IsNaN(v) || math.IsInf(v, 0) {
return true
}
return false
}
// CalcMovingPartitionsCount attempts to compute the number of
// moving partitions during a rebalance, given few node count
// statistics of the cluster
func CalcMovingPartitionsCount(numKeepNodes, numRemoveNodes, numNewNodes,
numPrevNodes, totalPartitions int) int {
// figure out the per node partitions to move during cases like
// scaleOut, scaleIn and constant nodecount in cluster
partitionsPerNode := 0
if numRemoveNodes == numNewNodes && numKeepNodes > 0 {
partitionsPerNode = totalPartitions / numKeepNodes
} else if numRemoveNodes > numNewNodes && numPrevNodes > 0 {
partitionsPerNode = totalPartitions / numPrevNodes
} else if numRemoveNodes < numNewNodes && numKeepNodes > 0 {
partitionsPerNode = totalPartitions / numKeepNodes
}
// adjust the partitionsPerNode for the rebalance scenario
// where both node additions and removals happen at the same time
delta := numRemoveNodes
if numRemoveNodes > 0 && numNewNodes > 0 {
delta = int(math.Abs(float64(numRemoveNodes - numNewNodes)))
}
return partitionsPerNode * (delta + numNewNodes)
}
var maxCallerStackDepth = 50
const panicCallStack = "panic callstack: \n"
// ReadableStackTrace tries to capture the caller stack frame
// for the calling function in a panic scenario.
func ReadableStackTrace() string {
callers := make([]uintptr, maxCallerStackDepth)
length := runtime.Callers(3, callers[:])
callers = callers[:length]
var result bytes.Buffer
frames := callersToFrames(callers)
for _, frame := range frames {
result.WriteString(fmt.Sprintf("%s:%d (%#x)\n\t%s\n",
frame.File, frame.Line, frame.PC, frame.Function))
}
return panicCallStack + result.String()
}
func callersToFrames(callers []uintptr) []runtime.Frame {
frames := make([]runtime.Frame, 0, len(callers))
framesPtr := runtime.CallersFrames(callers)
for {
frame, more := framesPtr.Next()
frames = append(frames, frame)
if !more {
return frames
}
}
}
func ParseOptionsInt(options map[string]string, configKey string) (int, bool) {
if val, exists := options[configKey]; exists && val != "" {
n, err := strconv.Atoi(val)
if err == nil {
log.Printf("parseOptionsInt: %s set to %d", configKey, n)
return n, exists
}
log.Warnf("parseOptionsInt: %s parse, err: %v", configKey, err)
}
return 0, false
}
func ParseOptionsBool(options map[string]string, configKey string) (bool, bool) {
if val, exists := options[configKey]; exists && val != "" {
v, err := strconv.ParseBool(val)
if err == nil {
log.Printf("parseOptionsBool: %s set to %t", configKey, v)
return v, exists
}
log.Warnf("parseOptionsBool: %s parse, err: %v", configKey, err)
}
return false, false
}
// GetDirectorySize computes the size of given directory
// recursively
func GetDirectorySize(path string) (int64, error) {
var dirSize int64
getSize := func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
dirSize += info.Size()
}
return err
}
err := filepath.Walk(path, getSize)
return dirSize, err
}