-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
516 lines (466 loc) · 12.1 KB
/
config.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
package config
import (
"errors"
"fmt"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
type Config struct {
lock sync.RWMutex
data map[string]string
toWatchLoaders []Loader
watchInterval time.Duration
stop chan bool
}
// Loader is used to load and parse configuration values from various formats and location
type Loader interface {
// Parse method is called
Parse() (map[string]string, error)
// IsWatchable method should return true if you need watch this loader
IsWatchable() bool
}
// single instance of the Config structure
var instance = &Config{
data: make(map[string]string),
watchInterval: time.Second * 10,
stop: make(chan bool),
toWatchLoaders: make([]Loader, 0),
}
//Get Instantiate new config reader
func Get() *Config {
return instance
}
func Load(loaders ...Loader) (*Config, error) {
return instance, instance.Load(loaders...)
}
// Has returns true if the given key exists
func (c *Config) Has(key string) bool {
c.lock.Lock()
_, ok := c.data[key]
c.lock.Unlock()
return ok
}
// SetWatchInterval sets interval of to automatic load configurations every duration, default interval is 5s
func (c *Config) SetWatchInterval(duration time.Duration) {
c.watchInterval = duration
}
// StopWatch stopping all watches
func (c *Config) StopWatch() {
c.stop <- true
}
// Load runs the given loaders in order to load and parse the configuration values. The first loader
// that returns an error stops the load process
func (c *Config) Load(loaders ...Loader) error {
c.lock.Lock()
defer c.lock.Unlock()
c.data = make(map[string]string)
// load content and parse and store in data
for _, loader := range loaders {
values, err := loader.Parse()
if err != nil {
return err
}
for k, v := range values {
c.data[k] = v
}
if loader.IsWatchable() {
c.toWatchLoaders = append(c.toWatchLoaders, loader)
}
}
go c.watch()
return nil
}
// GetString returns the value at the given key as a string and true if the key exists
// or empty string and false if the key doesn't exist
func (c *Config) GetString(key string) (string, bool) {
c.lock.RLock()
val, ok := c.data[key]
c.lock.RUnlock()
return c.resolveVar(val), ok
}
// GetFloat returns the value at the given key parsed as a float and true if the key exists
// or 0.0 and false if the key doesn't exist or failed to parse as a float64
func (c *Config) GetFloat(key string) (float64, bool) {
c.lock.RLock()
val, ok := c.data[key]
c.lock.RUnlock()
if !ok {
return 0, false
}
intVal, err := strconv.ParseFloat(c.resolveVar(val), 64)
if err != nil {
return 0, false
}
return intVal, true
}
// GetInt returns the value at the given key parsed as a int and true if the key exists
// or 0 and false if the key doesn't exist or failed to parse as a int
func (c *Config) GetInt(key string) (int, bool) {
v, ok := c.GetFloat(key)
return int(v), ok
}
// GetDuration returns the value at the given key parsed as Duration and true if the key exists
// or Duration(0) and false if the key doesn't exist or failed to parse as Duration
func (c *Config) GetDuration(key string) (time.Duration, bool) {
c.lock.RLock()
val, ok := c.data[key]
c.lock.RUnlock()
if !ok {
return 0, false
}
duration, err := ParseDuration(c.resolveVar(val))
if err != nil {
return 0, false
}
return duration, true
}
func (c *Config) resolveVar(val string) string {
reg := regexp.MustCompile(`(\${.[^}]*})`)
matches := reg.FindAllStringSubmatch(val, -1)
for _, match := range matches {
env := strings.TrimSuffix(strings.TrimPrefix(match[0], "${"), "}")
val = strings.ReplaceAll(val, match[0], os.Getenv(env))
}
if strings.HasPrefix(val, "${") && strings.HasSuffix(val, "}") {
val = strings.TrimSuffix(strings.TrimPrefix(val, "${"), "}")
return os.Getenv(val)
}
return val
}
// GetKeys return all loaded keys
func (c *Config) GetKeys() (res []string) {
c.lock.RLock()
for k := range c.data {
res = append(res, k)
}
c.lock.RUnlock()
return
}
var truthTable = map[string]bool{
"yes": true,
"on": true,
"true": true,
"1": true,
"active": true,
"set": true,
"enabled": true,
"no": false,
"off": false,
"false": false,
"0": false,
"inactive": false,
"unset": false,
"disabled": false,
}
// GetBool returns the value at the given key parsed as bool and true if the key exists
// or false and false if the key doesn't exist or failed to parse as a truthy value
func (c *Config) GetBool(key string) (bool, bool) {
c.lock.RLock()
val, ok := c.data[key]
c.lock.RUnlock()
if !ok {
return false, false
}
boolVal, ok := truthTable[strings.ToLower(c.resolveVar(val))]
if !ok {
return false, false
}
return boolVal, true
}
// Unmarshal decodes the configuration in a structure based on the `config` and `default` tags
func (c *Config) Unmarshal(destinationPtr interface{}) error {
rv := reflect.ValueOf(destinationPtr)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return errors.New("pointer_required")
}
pv := indirect(rv, false)
var v = pv
t := v.Type()
var err error
var defKey = "\x00\x01"
defer delete(c.data, defKey)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
defValue := field.Tag.Get("default")
cfgKey := field.Tag.Get("config")
if defValue == "" && cfgKey == "" {
continue
}
c.data[defKey] = defValue
fv := indirect(pv.Field(i), false)
if fv.CanSet() {
var v reflect.Value
if fv.Type().AssignableTo(reflect.TypeOf(time.Duration(0))) {
fv.Set(decode(reflect.ValueOf(c.GetDuration), cfgKey, defValue))
} else {
switch fv.Kind() {
case reflect.Bool:
v = decode(reflect.ValueOf(c.GetBool), cfgKey, defValue)
case reflect.String:
v = decode(reflect.ValueOf(c.GetString), cfgKey, defValue)
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Uint, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
v = decode(reflect.ValueOf(c.GetInt), cfgKey, defValue).Convert(fv.Type())
case reflect.Float32, reflect.Float64:
v = decode(reflect.ValueOf(c.GetFloat), cfgKey, defValue).Convert(fv.Type())
case reflect.Struct:
_ = c.Unmarshal(fv.Addr().Interface())
}
if v.IsValid() {
fv.Set(v)
} else if !v.IsValid() {
err = fmt.Errorf("%s not set value and don't have default value", cfgKey)
}
}
}
}
return err
}
func (c *Config) watch() {
timer := time.NewTimer(c.watchInterval)
for {
select {
case <-timer.C:
c.lock.Lock()
for _, loader := range c.toWatchLoaders {
values, err := loader.Parse()
if err != nil {
fmt.Println(err)
continue
}
for k, v := range values {
c.data[k] = v
}
}
c.lock.Unlock()
c.watch()
case <-c.stop:
timer.Stop()
return
}
}
}
func decode(fn reflect.Value, cfgKey, defValue string) reflect.Value {
if fn.Kind() == reflect.Func {
out := fn.Call([]reflect.Value{reflect.ValueOf(cfgKey)})
if out[1].Bool() {
return out[0]
} else if defValue != "" {
out := fn.Call([]reflect.Value{reflect.ValueOf("\x00\x01")})
return out[0]
}
}
return reflect.Value{}
}
var unitMap = map[string]int64{
"ns": int64(time.Nanosecond),
"us": int64(time.Microsecond),
"µs": int64(time.Microsecond), // U+00B5 = micro symbol
"μs": int64(time.Microsecond), // U+03BC = Greek letter mu
"ms": int64(time.Millisecond),
"s": int64(time.Second),
"m": int64(time.Minute),
"h": int64(time.Hour),
"d": int64(time.Hour * 24),
"w": int64(time.Hour * 24 * 7),
"M": int64(time.Hour * 24 * 7 * 30),
"y": int64(time.Hour * 24 * 7 * 30 * 12),
}
var errLeadingInt = errors.New("time: bad [0-9]*") // never printed
// leadingInt consumes the leading [0-9]* from s.
func leadingInt(s string) (x int64, rem string, err error) {
i := 0
for ; i < len(s); i++ {
c := s[i]
if c < '0' || c > '9' {
break
}
if x > (1<<63-1)/10 {
// overflow
return 0, "", errLeadingInt
}
x = x*10 + int64(c) - '0'
if x < 0 {
// overflow
return 0, "", errLeadingInt
}
}
return x, s[i:], nil
}
// leadingFraction consumes the leading [0-9]* from s.
// It is used only for fractions, so does not return an error on overflow,
// it just stops accumulating precision.
func leadingFraction(s string) (x int64, scale float64, rem string) {
i := 0
scale = 1
overflow := false
for ; i < len(s); i++ {
c := s[i]
if c < '0' || c > '9' {
break
}
if overflow {
continue
}
if x > (1<<63-1)/10 {
// It's possible for overflow to give a positive number, so take care.
overflow = true
continue
}
y := x*10 + int64(c) - '0'
if y < 0 {
overflow = true
continue
}
x = y
scale *= 10
}
return x, scale, s[i:]
}
// ParseDuration parses a duration string.
// A duration string is a possibly signed sequence of
// decimal numbers, each with optional fraction and a unit suffix,
// such as "300ms", "-1.5h" or "2h45m".
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
func ParseDuration(s string) (time.Duration, error) {
// [-+]?([0-9]*(\.[0-9]*)?[a-z]+)+
orig := s
var d int64
neg := false
// Consume [-+]?
if s != "" {
c := s[0]
if c == '-' || c == '+' {
neg = c == '-'
s = s[1:]
}
}
// Special case: if all that is left is "0", this is zero.
if s == "0" {
return 0, nil
}
if s == "" {
return 0, errors.New("time: invalid duration " + orig)
}
for s != "" {
var (
v, f int64 // integers before, after decimal point
scale float64 = 1 // value = v + f/scale
)
var err error
// The next character must be [0-9.]
if !(s[0] == '.' || '0' <= s[0] && s[0] <= '9') {
return 0, errors.New("time: invalid duration " + orig)
}
// Consume [0-9]*
pl := len(s)
v, s, err = leadingInt(s)
if err != nil {
return 0, errors.New("time: invalid duration " + orig)
}
pre := pl != len(s) // whether we consumed anything before a period
// Consume (\.[0-9]*)?
post := false
if s != "" && s[0] == '.' {
s = s[1:]
pl := len(s)
f, scale, s = leadingFraction(s)
post = pl != len(s)
}
if !pre && !post {
// no digits (e.g. ".s" or "-.s")
return 0, errors.New("time: invalid duration " + orig)
}
// Consume unit.
i := 0
for ; i < len(s); i++ {
c := s[i]
if c == '.' || '0' <= c && c <= '9' {
break
}
}
if i == 0 {
return 0, errors.New("time: missing unit in duration " + orig)
}
u := s[:i]
s = s[i:]
unit, ok := unitMap[u]
if !ok {
return 0, errors.New("time: unknown unit " + u + " in duration " + orig)
}
if v > (1<<63-1)/unit {
// overflow
return 0, errors.New("time: invalid duration " + orig)
}
v *= unit
if f > 0 {
// float64 is needed to be nanosecond accurate for fractions of hours.
// v >= 0 && (f*unit/scale) <= 3.6e+12 (ns/h, h is the largest unit)
v += int64(float64(f) * (float64(unit) / scale))
if v < 0 {
// overflow
return 0, errors.New("time: invalid duration " + orig)
}
}
d += v
if d < 0 {
// overflow
return 0, errors.New("time: invalid duration " + orig)
}
}
if neg {
d = -d
}
return time.Duration(d), nil
}
func indirect(v reflect.Value, decodingNull bool) reflect.Value {
v0 := v
haveAddr := false
// If v is a named type and is addressable,
// start with its address, so that if the type has pointer methods,
// we find them.
if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
haveAddr = true
v = v.Addr()
}
for {
// Load value from interface, but only if the result will be
// usefully addressable.
if v.Kind() == reflect.Interface && !v.IsNil() {
e := v.Elem()
if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) {
haveAddr = false
v = e
continue
}
}
if v.Kind() != reflect.Ptr {
break
}
if decodingNull && v.CanSet() {
break
}
// Prevent infinite loop if v is an interface pointing to its own address:
// var v interface{}
// v = &v
if v.Elem().Kind() == reflect.Interface && v.Elem().Elem() == v {
v = v.Elem()
break
}
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
if haveAddr {
v = v0 // restore original value after round-trip Value.Addr().Elem()
haveAddr = false
} else {
v = v.Elem()
}
}
return v
}