-
Notifications
You must be signed in to change notification settings - Fork 2
/
config_holder.go
286 lines (246 loc) · 7.25 KB
/
config_holder.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
package config
import (
"errors"
"fmt"
"os"
"os/signal"
"path"
"reflect"
"strings"
"sync"
"sync/atomic"
"syscall"
"github.com/asaskevich/govalidator"
"github.com/fsnotify/fsnotify"
"github.com/integration-system/bellows"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
jsoniter "github.com/json-iterator/go"
"github.com/mitchellh/mapstructure"
"github.com/mohae/deepcopy"
"github.com/spf13/viper"
)
const (
LocalConfigEnvPrefix = "LC_ISP"
RemoteConfigEnvPrefix = "RC_ISP"
)
var (
configInstance atomic.Value
remoteConfigInstance atomic.Value
startWatching = sync.Once{}
onChangeFunc interface{}
errInvalidFunc = errors.New("expecting func with two pointers to local config type")
reloadSig = syscall.SIGHUP
json = jsoniter.ConfigFastest
)
func init() {
ex, _ := os.Executable()
viper.SetEnvPrefix(LocalConfigEnvPrefix)
viper.AutomaticEnv()
envConfigName := "config"
configPath := path.Dir(ex)
if utils.DEV {
// _, filename, _, _ := runtime.Caller(0)
configPath = "./conf/"
}
if utils.EnvProfileName != "" {
envConfigName = "config_" + utils.EnvProfileName + ".yml"
}
if utils.EnvConfigPath != "" {
configPath = utils.EnvConfigPath
}
viper.SetConfigName(envConfigName)
viper.AddConfigPath(configPath)
}
func Get() interface{} {
return configInstance.Load()
}
func GetRemote() interface{} {
return remoteConfigInstance.Load()
}
func UnsafeSetRemote(remoteConfig interface{}) {
remoteConfigInstance.Store(remoteConfig)
}
func UnsafeSet(localConfig interface{}) {
configInstance.Store(localConfig)
}
func InitConfig(configuration interface{}) interface{} {
return InitConfigV2(configuration, false)
}
func InitConfigV2(localConfig interface{}, callOnChangeHandler bool) interface{} {
err := readLocalConfig(localConfig)
if err != nil {
log.Fatalf(stdcodes.ModuleReadLocalConfigError, "could not read local config: %v", err)
}
err = validateConfig(localConfig)
if err != nil {
log.Fatalf(stdcodes.ModuleInvalidLocalConfig, "invalid local config: %v", err)
}
configInstance.Store(localConfig)
if callOnChangeHandler {
handleConfigChange(localConfig, nil)
}
return localConfig
}
// Deprecated: use PrepareRemoteConfig and UnsafeSetRemote instead
func InitRemoteConfig(configuration interface{}, remoteConfig []byte) (interface{}, error) {
newConfiguration, newRemoteConfig, err := PrepareRemoteConfig(configuration, remoteConfig)
if err != nil {
return nil, err
}
if utils.DEV {
log.WithMetadata(log.Metadata{"config": string(newRemoteConfig)}).
Info(stdcodes.ConfigServiceReceiveConfiguration, "received remote config")
} else {
log.Info(stdcodes.ConfigServiceReceiveConfiguration, "received remote config")
}
remoteConfigInstance.Store(newConfiguration)
return newConfiguration, nil
}
func PrepareRemoteConfig(configuration interface{}, remoteConfig []byte) (interface{}, []byte, error) {
newRemoteConfig, err := overrideConfigurationFromEnv(remoteConfig, RemoteConfigEnvPrefix)
if err != nil {
if utils.DEV {
return nil, nil, fmt.Errorf("could not override remote config via env: %v\nconfig=%s", err, remoteConfig)
} else {
return nil, nil, fmt.Errorf("could not override remote config via env: %v", err)
}
}
newConfiguration := reflect.New(reflect.TypeOf(configuration).Elem()).Interface()
if err := json.Unmarshal(newRemoteConfig, newConfiguration); err != nil {
return nil, nil, fmt.Errorf("received invalid remote config: %v", err)
}
if err := validateConfig(newConfiguration); err != nil {
return nil, nil, fmt.Errorf("received invalid remote config: %v", err)
}
return newConfiguration, newRemoteConfig, nil
}
// Example:
// config.OnConfigChange(func(new, old *conf.Configuration) {
//
// })
// Callback call after initial loading and after every config files changing.
// On first call new and old configurations are equals
func OnConfigChange(f interface{}) {
rt := reflect.TypeOf(f)
if rt.Kind() != reflect.Func || rt.NumIn() != 2 {
panic(errInvalidFunc)
}
onChangeFunc = f
startWatching.Do(func() {
viper.WatchConfig()
viper.OnConfigChange(func(in fsnotify.Event) {
reloadConfig()
})
sigChan := make(chan os.Signal)
signal.Notify(sigChan, reloadSig)
go func() {
for {
_, ok := <-sigChan
if !ok {
return
}
reloadConfig()
}
}()
})
}
func reloadConfig() {
oldConfig := configInstance.Load()
newConfig := deepcopy.Copy(oldConfig)
err := readLocalConfig(newConfig)
if err != nil {
log.Errorf(stdcodes.ModuleReadLocalConfigError, "could not read local config: %v", err)
return
}
if err := validateConfig(newConfig); err != nil {
log.Errorf(stdcodes.ModuleInvalidLocalConfig, "invalid local config: %v", err)
return
}
configInstance.Store(newConfig)
handleConfigChange(newConfig, oldConfig)
}
func readLocalConfig(config interface{}) error {
squashStructsDecoderOption := func(dc *mapstructure.DecoderConfig) {
dc.Squash = true
}
if err := viper.ReadInConfig(); err != nil {
return fmt.Errorf("read local config file: %v", err)
} else if err := viper.Unmarshal(config, squashStructsDecoderOption); err != nil {
return fmt.Errorf("unmarshal config: %v", err)
}
return nil
}
func handleConfigChange(newConfig, oldConfig interface{}) {
if onChangeFunc == nil {
return
}
rv := reflect.ValueOf(onChangeFunc)
rt := rv.Type()
configType := reflect.TypeOf(newConfig).String()
newCfgType := rt.In(0).String()
oldCfgType := rt.In(1).String()
if newCfgType == oldCfgType && newCfgType == configType {
if oldConfig == nil {
oldConfig = newConfig
}
args := []reflect.Value{reflect.ValueOf(newConfig), reflect.ValueOf(oldConfig)}
rv.Call(args)
} else {
panic(errInvalidFunc)
}
}
func validateConfig(cfg interface{}) error {
if _, err := govalidator.ValidateStruct(cfg); err != nil {
validationErrors := govalidator.ErrorsByField(err)
if len(validationErrors) == 0 {
return err
}
str := strings.Builder{}
for k, v := range validationErrors {
str.WriteString(k)
str.WriteString(" -> ")
str.WriteString(v)
str.WriteString(", ")
}
return errors.New(str.String())
} else {
return nil
}
}
func overrideConfigurationFromEnv(src []byte, envPrefix string) ([]byte, error) {
envPrefix = envPrefix + "_"
overrides := getEnvOverrides(envPrefix)
if len(overrides) == 0 {
return src, nil
}
m := make(map[string]interface{})
err := json.Unmarshal(src, &m)
if err != nil {
return nil, fmt.Errorf("unmarshal to map: %v", err)
}
m = bellows.Flatten(m)
flattenMap := make(map[string]interface{}, len(m))
for k, v := range m {
flattenMap[strings.ToLower(k)] = v
}
for path, val := range overrides {
if newValue, err := castString(val); err != nil {
return nil, fmt.Errorf("could not override remote config variable %s, new value: %v, err: %v", path, val, err)
} else {
flattenMap[path] = newValue
}
}
expandedMap := bellows.Expand(flattenMap)
bytes, err := json.Marshal(expandedMap)
if err != nil {
return nil, fmt.Errorf("marhal to json: %v", err)
}
return bytes, nil
}
type CommonLocalConfig struct {
ModuleName string `valid:"required~Required"`
ConfigServiceAddress structure.AddressConfiguration `valid:"required~Required"`
}