-
Notifications
You must be signed in to change notification settings - Fork 701
/
conf.go
464 lines (393 loc) · 12.7 KB
/
conf.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
// Copyright 2020 Douyu
//
// 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 conf
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"reflect"
"strings"
"sync"
"time"
"github.com/douyu/jupiter/pkg/util/xcast"
"github.com/douyu/jupiter/pkg/util/xmap"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/spf13/cast"
)
// Configuration provides configuration for application.
type Configuration struct {
mu sync.RWMutex
override map[string]interface{}
keyDelim string
keyMap *sync.Map
onChanges []func(*Configuration)
onLoadeds []func(*Configuration)
watchers map[string][]func(*Configuration)
// TODO: concurrency protect
loaded bool
}
const (
defaultKeyDelim = "."
)
// New constructs a new Configuration with provider.
func New() *Configuration {
return &Configuration{
override: make(map[string]interface{}),
keyDelim: defaultKeyDelim,
keyMap: &sync.Map{},
onChanges: make([]func(*Configuration), 0),
onLoadeds: make([]func(*Configuration), 0),
watchers: make(map[string][]func(*Configuration)),
loaded: false,
}
}
// SetKeyDelim set keyDelim of a defaultConfiguration instance.
func (c *Configuration) SetKeyDelim(delim string) {
c.keyDelim = delim
}
// Sub returns new Configuration instance representing a sub tree of this instance.
func (c *Configuration) Sub(key string) *Configuration {
return &Configuration{
keyDelim: c.keyDelim,
override: c.GetStringMap(key),
}
}
// WriteConfig ...
func (c *Configuration) WriteConfig() error {
// return c.provider.Write(c.override)
return nil
}
// OnChange 注册change回调函数
func (c *Configuration) OnChange(fn func(*Configuration)) {
c.onChanges = append(c.onChanges, fn)
}
func (c *Configuration) OnLoaded(fn func(*Configuration)) {
if c.loaded {
fn(c)
return
}
c.onLoadeds = append(c.onLoadeds, fn)
}
// LoadEnvironments reads os environments with prefix such as APP_
// PREFIX_FIELD1_FIELD2 will be translated into prefix.field1.field2
func (c *Configuration) LoadEnvironments(prefix string) {
for _, env := range os.Environ() {
if !strings.HasPrefix(env, prefix) {
continue
}
key := strings.ToLower(strings.ReplaceAll(env, "_", "."))
val := os.Getenv(env)
_ = c.Set(key, val)
}
}
// LoadFromDataSource ...
func (c *Configuration) LoadFromDataSource(ds DataSource, unmarshaller Unmarshaller) error {
content, err := ds.ReadConfig()
if err != nil {
return err
}
if err := c.Load(content, unmarshaller); err != nil {
return err
}
if ds.IsConfigChanged() != nil {
go func() {
for range ds.IsConfigChanged() {
if content, err := ds.ReadConfig(); err == nil {
_ = c.reflush(content, unmarshaller)
for _, change := range c.onChanges {
change(c)
}
}
}
}()
}
return nil
}
func (c *Configuration) reflush(content []byte, unmarshal Unmarshaller) error {
configuration := make(map[string]interface{})
if err := unmarshal(content, &configuration); err != nil {
return err
}
if err := c.apply(configuration); err != nil {
return err
}
return nil
}
// Load ...
func (c *Configuration) Load(content []byte, unmarshal Unmarshaller) error {
if err := c.reflush(content, unmarshal); err != nil {
return err
}
log.Print("load config successfully")
c.loaded = true
for _, loadHook := range c.onLoadeds {
loadHook(c)
}
return nil
}
// Load loads configuration from provided data source.
func (c *Configuration) LoadFromReader(reader io.Reader, unmarshaller Unmarshaller) error {
content, err := ioutil.ReadAll(reader)
if err != nil {
return err
}
return c.Load(content, unmarshaller)
}
func (c *Configuration) apply(conf map[string]interface{}) error {
c.mu.Lock()
defer c.mu.Unlock()
var changes = make(map[string]interface{})
xmap.MergeStringMap(c.override, conf)
for k, v := range c.traverse(c.keyDelim) {
orig, ok := c.keyMap.Load(k)
if ok && !reflect.DeepEqual(orig, v) {
changes[k] = v
}
c.keyMap.Store(k, v)
}
if len(changes) > 0 {
c.notifyChanges(changes)
}
return nil
}
func (c *Configuration) notifyChanges(changes map[string]interface{}) {
var changedWatchPrefixMap = map[string]struct{}{}
for watchPrefix := range c.watchers {
for key := range changes {
// 前缀匹配即可
// todo 可能产生错误匹配
if strings.HasPrefix(key, watchPrefix) {
changedWatchPrefixMap[watchPrefix] = struct{}{}
}
}
}
for changedWatchPrefix := range changedWatchPrefixMap {
for _, handle := range c.watchers[changedWatchPrefix] {
go handle(c)
}
}
}
// Set ...
func (c *Configuration) Set(key string, val interface{}) error {
paths := strings.Split(key, c.keyDelim)
lastKey := paths[len(paths)-1]
m := deepSearch(c.override, paths[:len(paths)-1])
m[lastKey] = val
return c.apply(m)
// c.keyMap.Store(key, val)
}
func deepSearch(m map[string]interface{}, path []string) map[string]interface{} {
for _, k := range path {
m2, ok := m[k]
if !ok {
m3 := make(map[string]interface{})
m[k] = m3
m = m3
continue
}
m3, ok := m2.(map[string]interface{})
if !ok {
m3 = make(map[string]interface{})
m[k] = m3
}
m = m3
}
return m
}
// Get returns the value associated with the key
func (c *Configuration) Get(key string) interface{} {
return c.find(key)
}
// GetString returns the value associated with the key as a string with default defaultConfiguration.
func GetString(key string) string {
return defaultConfiguration.GetString(key)
}
// GetString returns the value associated with the key as a string.
func (c *Configuration) GetString(key string) string {
return cast.ToString(c.Get(key))
}
// GetBool returns the value associated with the key as a boolean with default defaultConfiguration.
func GetBool(key string) bool {
return defaultConfiguration.GetBool(key)
}
// GetBool returns the value associated with the key as a boolean.
func (c *Configuration) GetBool(key string) bool {
return cast.ToBool(c.Get(key))
}
// GetInt returns the value associated with the key as an integer with default defaultConfiguration.
func GetInt(key string) int {
return defaultConfiguration.GetInt(key)
}
// GetInt returns the value associated with the key as an integer.
func (c *Configuration) GetInt(key string) int {
return cast.ToInt(c.Get(key))
}
// GetInt64 returns the value associated with the key as an integer with default defaultConfiguration.
func GetInt64(key string) int64 {
return defaultConfiguration.GetInt64(key)
}
// GetInt64 returns the value associated with the key as an integer.
func (c *Configuration) GetInt64(key string) int64 {
return cast.ToInt64(c.Get(key))
}
// GetInt64Slice returns the value associated with the key as an integer slice with default defaultConfiguration.
func GetInt64Slice(key string) []int64 {
return defaultConfiguration.GetInt64Slice(key)
}
// GetInt64Slice returns the value associated with the key as an integer slice.
func (c *Configuration) GetInt64Slice(key string) []int64 {
return xcast.ToInt64Slice(key)
}
// GetFloat64 returns the value associated with the key as a float64 with default defaultConfiguration.
func GetFloat64(key string) float64 {
return defaultConfiguration.GetFloat64(key)
}
// GetFloat64 returns the value associated with the key as a float64.
func (c *Configuration) GetFloat64(key string) float64 {
return cast.ToFloat64(c.Get(key))
}
// GetTime returns the value associated with the key as time with default defaultConfiguration.
func GetTime(key string) time.Time {
return defaultConfiguration.GetTime(key)
}
// GetTime returns the value associated with the key as time.
func (c *Configuration) GetTime(key string) time.Time {
return cast.ToTime(c.Get(key))
}
// GetDuration returns the value associated with the key as a duration with default defaultConfiguration.
func GetDuration(key string) time.Duration {
return defaultConfiguration.GetDuration(key)
}
// GetDuration returns the value associated with the key as a duration.
func (c *Configuration) GetDuration(key string) time.Duration {
return cast.ToDuration(c.Get(key))
}
// GetStringSlice returns the value associated with the key as a slice of strings with default defaultConfiguration.
func GetStringSlice(key string) []string {
return defaultConfiguration.GetStringSlice(key)
}
// GetStringSlice returns the value associated with the key as a slice of strings.
func (c *Configuration) GetStringSlice(key string) []string {
return cast.ToStringSlice(c.Get(key))
}
// GetSlice returns the value associated with the key as a slice of strings with default defaultConfiguration.
func GetSlice(key string) []interface{} {
return defaultConfiguration.GetSlice(key)
}
// GetSlice returns the value associated with the key as a slice of strings.
func (c *Configuration) GetSlice(key string) []interface{} {
return cast.ToSlice(c.Get(key))
}
// GetStringMap returns the value associated with the key as a map of interfaces with default defaultConfiguration.
func GetStringMap(key string) map[string]interface{} {
return defaultConfiguration.GetStringMap(key)
}
// GetStringMap returns the value associated with the key as a map of interfaces.
func (c *Configuration) GetStringMap(key string) map[string]interface{} {
return cast.ToStringMap(c.Get(key))
}
// GetStringMapString returns the value associated with the key as a map of strings with default defaultConfiguration.
func GetStringMapString(key string) map[string]string {
return defaultConfiguration.GetStringMapString(key)
}
// GetStringMapString returns the value associated with the key as a map of strings.
func (c *Configuration) GetStringMapString(key string) map[string]string {
return cast.ToStringMapString(c.Get(key))
}
// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings with default defaultConfiguration.
func GetStringMapStringSlice(key string) map[string][]string {
return defaultConfiguration.GetStringMapStringSlice(key)
}
// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
func (c *Configuration) GetStringMapStringSlice(key string) map[string][]string {
return cast.ToStringMapStringSlice(c.Get(key))
}
// UnmarshalWithExpect unmarshal key, returns expect if failed
func UnmarshalWithExpect(key string, expect interface{}) interface{} {
return defaultConfiguration.UnmarshalWithExpect(key, expect)
}
// UnmarshalWithExpect unmarshal key, returns expect if failed
func (c *Configuration) UnmarshalWithExpect(key string, expect interface{}) interface{} {
err := c.UnmarshalKey(key, expect)
if err != nil {
return expect
}
return expect
}
// UnmarshalKey takes a single key and unmarshal it into a Struct with default defaultConfiguration.
func UnmarshalKey(key string, rawVal interface{}, opts ...GetOption) error {
return defaultConfiguration.UnmarshalKey(key, rawVal, opts...)
}
// ErrInvalidKey ...
var ErrInvalidKey = errors.New("invalid key, maybe not exist in config")
// UnmarshalKey takes a single key and unmarshal it into a Struct.
func (c *Configuration) UnmarshalKey(key string, rawVal interface{}, opts ...GetOption) error {
var options = defaultGetOptions
for _, opt := range opts {
opt(&options)
}
config := mapstructure.DecoderConfig{
DecodeHook: mapstructure.StringToTimeDurationHookFunc(),
Result: rawVal,
TagName: options.TagName,
}
decoder, err := mapstructure.NewDecoder(&config)
if err != nil {
return err
}
if key == "" {
c.mu.RLock()
defer c.mu.RUnlock()
return decoder.Decode(c.override)
}
value := c.Get(key)
if value == nil {
return errors.Wrap(ErrInvalidKey, key)
}
return decoder.Decode(value)
}
func (c *Configuration) find(key string) interface{} {
dd, ok := c.keyMap.Load(key)
if ok {
return dd
}
paths := strings.Split(key, c.keyDelim)
c.mu.RLock()
defer c.mu.RUnlock()
m := xmap.DeepSearchInMap(c.override, paths[:len(paths)-1]...)
dd = m[paths[len(paths)-1]]
c.keyMap.Store(key, dd)
return dd
}
func lookup(prefix string, target map[string]interface{}, data map[string]interface{}, sep string) {
for k, v := range target {
pp := fmt.Sprintf("%s%s%s", prefix, sep, k)
if prefix == "" {
pp = k
}
if dd, err := cast.ToStringMapE(v); err == nil {
lookup(pp, dd, data, sep)
} else {
data[pp] = v
}
}
}
func (c *Configuration) traverse(sep string) map[string]interface{} {
data := make(map[string]interface{})
lookup("", c.override, data, sep)
return data
}