-
Notifications
You must be signed in to change notification settings - Fork 7
/
config.go
344 lines (282 loc) · 12.2 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
// Package config handles the configuration of the program.
// The configuration contains the set of initial parameter settings that are read at run-time by the program.
// This package allows to load the configuration from a local file, an environment variable or a remote config provider (e.g. Consul, ETCD, Firestore).
//
// Configuration Loading Strategy:
//
// Different entry points can be used during the development, debugging, testing or deployment.
//
// To get the maximum flexibility, the different configuration entry points can be coordinated in the following sequence (1 has the lowest priority and 5 the maximum):
//
// 1. In the “myprog” program the configuration parameters are defined as a data structure that can be easily mapped to and from a JSON (or YAML) object, and they are initialized with constant default values;
//
// 2. The program attempts to load the local “config.json” configuration file (or what is specified by defaultConfigName and defaultConfigType) and, as soon one is found, overwrites the values previously set. The configuration file is searched in the following ordered directories:
// ./
// ~/.myprog/
// /etc/myprog/
//
// 3. The program attempts to load the environmental variables that define the remote configuration system and, if found, overwrites the correspondent configuration parameters:
// MYPROG_REMOTECONFIGPROVIDER → remoteConfigProvider
// MYPROG_REMOTECONFIGENDPOINT → remoteConfigEndpoint
// MYPROG_REMOTECONFIGPATH → remoteConfigPath
// MYPROG_REMOTECONFIGSECRETKEYRING → remoteConfigSecretKeyring
// MYPROG_REMOTECONFIGDATA → remoteConfigData
//
// 4. If the remoteConfigProvider parameter is not empty, the program attempts to load the configuration data from the specified source. This can be any remote source supported by the Viper library (e.g. Consul, ETCD) or alternatively from the MYPROG_REMOTECONFIGDATA environment variable as base64 encoded JSON if MYPROG_REMOTECONFIGPROVIDER is set to "envar".
//
// 5. Any specified command line property overwrites the correspondent configuration parameter.
//
// 6. The configuration parameters are validated via the Validate() function.
//
// An example can be found in examples/service/internal/cli/config.go
package config
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"strings"
"github.com/spf13/pflag"
"github.com/spf13/viper"
_ "github.com/spf13/viper/remote" //nolint:revive,nolintlint
)
// General constants.
const (
defaultConfigName = "config" // Base name of the file containing the configuration data.
defaultConfigType = "json" // Type of configuration data.)
providerEnvVar = "envvar"
)
// Remote configuration key names.
const (
keyRemoteConfigProvider = "remoteConfigProvider"
keyRemoteConfigEndpoint = "remoteConfigEndpoint"
keyRemoteConfigPath = "remoteConfigPath"
keyRemoteConfigSecretKeyring = "remoteConfigSecretKeyring" //nolint:gosec
keyRemoteConfigData = "remoteConfigData"
)
// Remote configuration default values.
const (
defaultRemoteConfigProvider = ""
defaultRemoteConfigEndpoint = ""
defaultRemoteConfigPath = ""
defaultRemoteConfigSecretKeyring = ""
)
// Logger configuration key names.
const (
keyLogAddress = "log.address"
keyLogFormat = "log.format"
keyLogLevel = "log.level"
keyLogNetwork = "log.network"
)
// Logger configuration default values.
const (
defaultLogFormat = "JSON"
defaultLogLevel = "DEBUG"
defaultLogAddress = ""
defaultLogNetwork = ""
)
// Extra parameters key names.
const (
keyShutdownTimeout = "shutdown_timeout"
)
// Extra parameters default values.
const (
defaultShutdownTimeout = 30 // time in seconds to wait on exit for a graceful shutdown.
)
// Configuration is the interface we need the application config struct to implement.
type Configuration interface {
SetDefaults(v Viper)
Validate() error
}
// Viper is the local interface to the actual viper to allow for mocking.
//
//nolint:interfacebloat
type Viper interface {
AddConfigPath(in string)
AddRemoteProvider(provider, endpoint, path string) error
AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error
AllKeys() []string
AutomaticEnv()
BindEnv(input ...string) error
BindPFlag(key string, flag *pflag.Flag) error
Get(key string) any
ReadConfig(in io.Reader) error
ReadInConfig() error
ReadRemoteConfig() error
SetConfigName(in string)
SetConfigType(in string)
SetDefault(key string, value any)
SetEnvPrefix(in string)
Unmarshal(rawVal any, opts ...viper.DecoderConfigOption) error
}
// BaseConfig contains the default configuration options to be used in the application config struct.
type BaseConfig struct {
// Log configuration.
Log LogConfig `mapstructure:"log" validate:"required"`
// ShutdownTimeout is the time in seconds to wait for graceful shutdown.
ShutdownTimeout int64 `mapstructure:"shutdown_timeout" validate:"omitempty,min=1,max=3600"`
}
// LogConfig contains the configuration for the application logger.
type LogConfig struct {
// Level is the standard syslog level: EMERGENCY, ALERT, CRITICAL, ERROR, WARNING, NOTICE, INFO, DEBUG.
Level string `mapstructure:"level" validate:"required,oneof=EMERGENCY ALERT CRITICAL ERROR WARNING NOTICE INFO DEBUG"`
// Format is the log output format: CONSOLE, JSON.
Format string `mapstructure:"format" validate:"required,oneof=CONSOLE JSON"`
// Network is the optional network protocol used to send logs via syslog: udp, tcp.
Network string `mapstructure:"network" validate:"omitempty,oneof=udp tcp"`
// Address is the optional remote syslog network address: (ip:port) or just (:port).
Address string `mapstructure:"address" validate:"omitempty,hostname_port"`
}
// remoteSourceConfig contains the default remote source options to be used in the application config struct.
type remoteSourceConfig struct {
// Provider is the optional external configuration source: consul, etcd, firestore, envvar.
// When envvar is set the data shoul dbe set in the Data field.
Provider string `mapstructure:"remoteConfigProvider" validate:"omitempty,oneof=consul etcd firestore envvar"`
// Endpoint is the remote configuration URL (ip:port).
Endpoint string `mapstructure:"remoteConfigEndpoint" validate:"omitempty,url|hostname_port"`
// Path is the remote configuration path where to search fo the configuration file ("/cli/program").
Path string `mapstructure:"remoteConfigPath" validate:"omitempty,file"`
// SecretKeyring is the path to the openpgp secret keyring used to decript the remote configuration data (e.g.: "/etc/program/configkey.gpg")
SecretKeyring string `mapstructure:"remoteConfigSecretKeyring" validate:"omitempty,file"`
// Data is the base64 encoded JSON configuration data to be used with the "envvar" provider.
Data string `mapstructure:"remoteConfigData" validate:"required_if=Provider envar,omitempty,base64"`
}
// Load populates the configuration parameters.
func Load(cmdName, configDir, envPrefix string, cfg Configuration) error {
localViper := viper.New()
remoteViper := viper.New()
return loadConfig(localViper, remoteViper, cmdName, configDir, envPrefix, cfg)
}
// loadConfig loads the configuration.
func loadConfig(localViper, remoteViper Viper, cmdName, configDir, envPrefix string, cfg Configuration) error {
remoteSourceCfg, err := loadLocalConfig(localViper, cmdName, configDir, envPrefix, cfg)
if err != nil {
return fmt.Errorf("failed loading local configuration: %w", err)
}
if err := loadRemoteConfig(localViper, remoteViper, remoteSourceCfg, envPrefix, cfg); err != nil {
return fmt.Errorf("failed loading remote configuration: %w", err)
}
if err := cfg.Validate(); err != nil {
return fmt.Errorf("failed validating configuration: %w", err)
}
return nil
}
// loadLocalConfig returns the local configuration parameters.
func loadLocalConfig(v Viper, cmdName, configDir, envPrefix string, cfg Configuration) (*remoteSourceConfig, error) {
// set default remote configuration values
v.SetDefault(keyRemoteConfigProvider, defaultRemoteConfigProvider)
v.SetDefault(keyRemoteConfigEndpoint, defaultRemoteConfigEndpoint)
v.SetDefault(keyRemoteConfigPath, defaultRemoteConfigPath)
v.SetDefault(keyRemoteConfigSecretKeyring, defaultRemoteConfigSecretKeyring)
// set default logging configuration values
v.SetDefault(keyLogFormat, defaultLogFormat)
v.SetDefault(keyLogLevel, defaultLogLevel)
v.SetDefault(keyLogAddress, defaultLogAddress)
v.SetDefault(keyLogNetwork, defaultLogNetwork)
// set default config name and type
v.SetConfigName(defaultConfigName)
v.SetConfigType(defaultConfigType)
// add default search paths
configureSearchPath(v, cmdName, configDir)
// set application defaults
v.SetDefault(keyShutdownTimeout, defaultShutdownTimeout)
// set defaults from application configuration
cfg.SetDefaults(v)
// support environment variables for the remote configuration
v.AutomaticEnv()
v.SetEnvPrefix(strings.ReplaceAll(envPrefix, "-", "_")) // will be uppercased automatically
envVar := []string{
keyRemoteConfigProvider,
keyRemoteConfigEndpoint,
keyRemoteConfigPath,
keyRemoteConfigSecretKeyring,
keyRemoteConfigData,
}
for _, ev := range envVar {
_ = v.BindEnv(ev) // we ignore the error because we are always passing an argument value
}
// Find and read the local configuration file (if any)
if err := v.ReadInConfig(); err != nil {
return nil, fmt.Errorf("failed reading in config: %w", err)
}
var rsCfg remoteSourceConfig
if err := v.Unmarshal(&rsCfg); err != nil {
return nil, fmt.Errorf("failed unmarshalling config: %w", err)
}
return &rsCfg, nil
}
// loadRemoteConfig returns the remote configuration parameters.
func loadRemoteConfig(lv Viper, rv Viper, rs *remoteSourceConfig, envPrefix string, cfg Configuration) error {
for _, k := range lv.AllKeys() {
rv.SetDefault(k, lv.Get(k))
}
rv.SetConfigType(defaultConfigType)
var err error
switch rs.Provider {
case "":
// ignore remote source
case providerEnvVar:
err = loadFromEnvVarSource(rv, rs, envPrefix)
default:
err = loadFromRemoteSource(rv, rs, envPrefix)
}
if err != nil {
return fmt.Errorf("failed loading configuration from remote source: %w", err)
}
if err := rv.Unmarshal(cfg); err != nil {
return fmt.Errorf("failed loading application configuration: %w", err)
}
return nil
}
// loadFromEnvVarSource loads the configuration data from an environment variable.
// The data must be base64-encoded.
func loadFromEnvVarSource(v Viper, rc *remoteSourceConfig, envPrefix string) error {
if rc.Data == "" {
return validationError(rc.Provider, envPrefix, keyRemoteConfigData)
}
data, err := base64.StdEncoding.DecodeString(rc.Data)
if err != nil {
return fmt.Errorf("failed decoding config data: %w", err)
}
return v.ReadConfig(bytes.NewReader(data)) //nolint:wrapcheck
}
// loadFromRemoteSource loads the configuration data from a remote source or service.
func loadFromRemoteSource(v Viper, rc *remoteSourceConfig, envPrefix string) error {
if rc.Endpoint == "" {
return validationError(rc.Provider, envPrefix, keyRemoteConfigEndpoint)
}
if rc.Path == "" {
return validationError(rc.Provider, envPrefix, keyRemoteConfigPath)
}
var err error
if rc.SecretKeyring == "" {
err = v.AddRemoteProvider(rc.Provider, rc.Endpoint, rc.Path)
} else {
err = v.AddSecureRemoteProvider(rc.Provider, rc.Endpoint, rc.Path, rc.SecretKeyring)
}
if err != nil {
return fmt.Errorf("failed adding remote config provider: %w", err)
}
return v.ReadRemoteConfig() //nolint:wrapcheck
}
// configureSearchPath sets the directory paths to search in order for a local configuration file.
func configureSearchPath(v Viper, cmdName, configDir string) {
var configSearchPath []string
if configDir != "" {
// add the configuration directory specified as program argument
configSearchPath = append(configSearchPath, configDir)
}
// add default search directories for the configuration file
configSearchPath = append(configSearchPath, []string{
"./",
"$HOME/." + cmdName + "/",
"/etc/" + cmdName + "/",
}...)
for _, p := range configSearchPath {
v.AddConfigPath(p)
}
}
// validationError returns a validation error.
func validationError(provider, envPrefix, varName string) error {
return fmt.Errorf("%s config provider requires %s_%s to be set", provider, strings.ToUpper(envPrefix), strings.ToUpper(varName))
}