-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
271 lines (214 loc) · 7.24 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
package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"dario.cat/mergo"
"github.com/go-viper/mapstructure/v2"
yamlParser "github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/confmap"
"github.com/knadh/koanf/providers/env"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/providers/posflag"
"github.com/knadh/koanf/providers/structs"
"github.com/knadh/koanf/v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/rs/zerolog/log"
"gopkg.in/yaml.v3"
)
const (
envPrefix = "SQUIRRELDB_"
delimiter = "."
)
var (
errWrongMapFormat = errors.New("could not parse map from string")
ErrInvalidValue = errors.New("invalid config value")
)
type Warnings error
// Load loads the configuration from files and directories to a struct.
// Returns the config, warnings and an error.
func Load(withDefaultAndFlags bool, paths ...string) (Config, Warnings, error) {
cfg, warnings, err := loadToStruct(withDefaultAndFlags, os.Args, paths...)
return cfg, warnings.MaybeUnwrap(), err
}
func loadToStruct(withDefaultAndFlags bool, args []string, paths ...string) (Config, prometheus.MultiError, error) {
k, warnings, err := load(withDefaultAndFlags, args, paths...)
var config Config
unmarshalConf := koanf.UnmarshalConf{
DecoderConfig: &mapstructure.DecoderConfig{
DecodeHook: mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToSliceHookFunc(","),
mapstructure.TextUnmarshallerHookFunc(),
mapstructure.StringToTimeDurationHookFunc(),
intToTimeDurationHookFunc(),
stringToMapHookFunc(),
),
Metadata: nil,
ErrorUnused: true,
Result: &config,
WeaklyTypedInput: true,
},
Tag: "yaml",
}
warning := k.UnmarshalWithConf("", &config, unmarshalConf)
warnings.Append(warning)
return config, unwrapErrors(warnings), err
}
// load the configuration from files and directories.
func load(withDefaultAndFlags bool, args []string, paths ...string) (*koanf.Koanf, prometheus.MultiError, error) {
fileEnvKoanf, warnings, errors := loadPaths(paths)
// Load config from environment variables.
// The warnings are filled only after k.Load is called.
envToKey, envWarnings := envToKeyFunc()
// Environment variable overwrite basic types (string, int), arrays, and maps.
envMergeFunc := mergeFunc(mergo.WithOverride)
warning := fileEnvKoanf.Load(env.Provider(envPrefix, delimiter, envToKey), nil, envMergeFunc)
warnings.Append(warning)
if len(*envWarnings) > 0 {
warnings = append(warnings, *envWarnings...)
}
// Load default values.
k := koanf.New(delimiter)
if withDefaultAndFlags {
warning = k.Load(structsProvider(DefaultConfig(), "yaml"), nil)
warnings.Append(warning)
}
// Merge defaults and config from files and environment.
// The config overwrites the defaults for basic types (string, int) and arrays, and merges maps.
warning = k.Load(confmap.Provider(fileEnvKoanf.All(), delimiter), nil, mergeFunc(mergo.WithOverride))
warnings.Append(warning)
if withDefaultAndFlags {
// Parse the config flags without the command flags because the command flags would
// create warnings about invalid keys when the config is converted to a struct.
flagSet := flagSetFromFlags(configFlags())
// The error can be safely ignored as the flags were already parsed in the daemon.
_ = flagSet.Parse(args)
// Overwrite the config with the command line args set explicitly.
warning = k.Load(posflag.Provider(flagSet, delimiter, k), nil)
warnings.Append(warning)
}
return k, warnings, errors.MaybeUnwrap()
}
// envToKeyFunc returns a function that converts an environment variable to a configuration key
// and a pointer to Warnings, the warnings are filled only after koanf.Load has been called.
// Panics if two config keys correspond to the same environment variable.
func envToKeyFunc() (func(string) string, *prometheus.MultiError) {
// Get all config keys from an empty config.
k := koanf.New(delimiter)
_ = k.Load(structs.Provider(Config{}, "yaml"), nil)
allKeys := k.All()
// Build a map of the environment variables with their corresponding config keys.
envToKey := make(map[string]string, len(allKeys))
for key := range allKeys {
envKey := toEnvKey(key)
if oldKey, exists := envToKey[envKey]; exists {
err := fmt.Sprintf(
"Conflict between config keys, %s and %s both corresponds to the variable %s",
oldKey, key, envKey,
)
panic(err)
}
envToKey[envKey] = key
}
warnings := make(prometheus.MultiError, 0)
envFunc := func(s string) string {
return envToKey[s]
}
return envFunc, &warnings
}
// mergeFunc return a merge function to use with koanf.
func mergeFunc(opts ...func(*mergo.Config)) koanf.Option {
merge := func(src, dest map[string]interface{}) error {
err := mergo.Merge(&dest, src, opts...)
if err != nil {
log.Err(err).Msg("Failed to merge config")
}
return err
}
return koanf.WithMergeFunc(merge)
}
// toEnvKey returns the environment variable corresponding to a configuration key.
// For instance: toEnvKey("web.enable") -> GLOUTON_WEB_ENABLE.
func toEnvKey(key string) string {
envKey := strings.ToUpper(key)
envKey = envPrefix + strings.ReplaceAll(envKey, ".", "_")
return envKey
}
// loadPaths returns the config loaded from the given paths, warnings and errors.
func loadPaths(paths []string) (*koanf.Koanf, prometheus.MultiError, prometheus.MultiError) {
var warnings, errors prometheus.MultiError
k := koanf.New(delimiter)
for _, path := range paths {
stat, err := os.Stat(path)
if err != nil && os.IsNotExist(err) {
// Ignore missing config files.
continue
}
if err != nil {
errors.Append(err)
continue
}
if stat.IsDir() {
moreWarnings, err := loadDirectory(k, path)
errors.Append(err)
if moreWarnings != nil {
warnings = append(warnings, moreWarnings...)
}
} else {
warning := loadFile(k, path)
warnings.Append(warning)
}
}
return k, warnings, errors
}
func loadDirectory(k *koanf.Koanf, dirPath string) (prometheus.MultiError, error) {
files, err := os.ReadDir(dirPath)
if err != nil {
return nil, err
}
var warnings prometheus.MultiError
for _, f := range files {
if !strings.HasSuffix(f.Name(), ".conf") {
continue
}
path := filepath.Join(dirPath, f.Name())
warning := loadFile(k, path)
warnings.Append(warning)
}
return warnings, nil
}
func loadFile(k *koanf.Koanf, path string) error {
// Merge this file with the previous config.
// Overwrite values, merge maps and append slices.
err := k.Load(file.Provider(path), yamlParser.Parser(), mergeFunc(mergo.WithOverride, mergo.WithAppendSlice))
if err != nil {
return fmt.Errorf("failed to load '%s': %w", path, err)
}
return nil
}
// unwrapErrors unwrap all errors in the list than contain multiple errors.
func unwrapErrors(errs prometheus.MultiError) prometheus.MultiError {
if len(errs) == 0 {
return nil
}
unwrapped := make(prometheus.MultiError, 0, len(errs))
for _, err := range errs {
var (
mapErr *mapstructure.Error
yamlErr *yaml.TypeError
)
switch {
case errors.As(err, &mapErr):
unwrapped = append(unwrapped, mapErr.WrappedErrors()...)
case errors.As(err, &yamlErr):
for _, wrappedErr := range yamlErr.Errors {
unwrapped.Append(errors.New(wrappedErr)) //nolint:goerr113
}
default:
unwrapped.Append(err)
}
}
return unwrapped
}