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
|
/*
Copyright 2013-2014 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License version 3, as published
by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranties of
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Package config has helpers to parse and use JSON based configuration.
package config
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
)
func checkDestConfig(name string, destConfig interface{}) (reflect.Value, error) {
destValue := reflect.ValueOf(destConfig)
if destValue.Kind() != reflect.Ptr || destValue.Elem().Kind() != reflect.Struct {
return reflect.Value{}, fmt.Errorf("%s not *struct", name)
}
return destValue, nil
}
type destField struct {
fld reflect.StructField
dest interface{}
}
func (f destField) configName() string {
fld := f.fld
configName := strings.Split(fld.Tag.Get("json"), ",")[0]
if configName == "" {
configName = strings.ToLower(fld.Name[:1]) + fld.Name[1:]
}
return configName
}
func traverseStruct(destStruct reflect.Value) <-chan destField {
ch := make(chan destField)
var traverse func(reflect.Value, chan<- destField)
traverse = func(destStruct reflect.Value, ch chan<- destField) {
structType := destStruct.Type()
n := structType.NumField()
for i := 0; i < n; i++ {
fld := structType.Field(i)
val := destStruct.Field(i)
if fld.PkgPath != "" { // unexported
continue
}
if fld.Anonymous {
traverse(val, ch)
continue
}
ch <- destField{
fld: fld,
dest: val.Addr().Interface(),
}
}
}
go func() {
traverse(destStruct, ch)
close(ch)
}()
return ch
}
func fillDestConfig(destValue reflect.Value, p map[string]json.RawMessage) error {
destStruct := destValue.Elem()
for destField := range traverseStruct(destStruct) {
configName := destField.configName()
raw, found := p[configName]
if !found { // assume all fields are mandatory for now
return fmt.Errorf("missing %s", configName)
}
dest := destField.dest
err := json.Unmarshal([]byte(raw), dest)
if err != nil {
return fmt.Errorf("%s: %v", configName, err)
}
}
return nil
}
// ReadConfig reads a JSON configuration into destConfig which should
// be a pointer to a structure. It does some more configuration
// specific error checking than plain JSON decoding, and mentions
// fields in errors. Configuration fields in the JSON object are
// expected to start with lower case.
func ReadConfig(r io.Reader, destConfig interface{}) error {
destValue, err := checkDestConfig("destConfig", destConfig)
if err != nil {
return err
}
// do the parsing in two phases for better error handling
var p1 map[string]json.RawMessage
err = json.NewDecoder(r).Decode(&p1)
if err != nil {
return err
}
return fillDestConfig(destValue, p1)
}
// FromString are config holders that can be set by parsing a string.
type FromString interface {
SetFromString(enc string) error
}
// UnmarshalJSONViaString helps unmarshalling from JSON for FromString
// supporting config holders.
func UnmarshalJSONViaString(dest FromString, b []byte) error {
var enc string
err := json.Unmarshal(b, &enc)
if err != nil {
return err
}
return dest.SetFromString(enc)
}
// ConfigTimeDuration can hold a time.Duration in a configuration struct,
// that is parsed from a string as supported by time.ParseDuration.
type ConfigTimeDuration struct {
time.Duration
}
func (ctd *ConfigTimeDuration) UnmarshalJSON(b []byte) error {
return UnmarshalJSONViaString(ctd, b)
}
func (ctd *ConfigTimeDuration) SetFromString(enc string) error {
v, err := time.ParseDuration(enc)
if err != nil {
return err
}
*ctd = ConfigTimeDuration{v}
return nil
}
// TimeDuration returns the time.Duration held in ctd.
func (ctd ConfigTimeDuration) TimeDuration() time.Duration {
return ctd.Duration
}
// ConfigHostPort can hold a host:port string in a configuration struct.
type ConfigHostPort string
func (chp *ConfigHostPort) UnmarshalJSON(b []byte) error {
return UnmarshalJSONViaString(chp, b)
}
func (chp *ConfigHostPort) SetFromString(enc string) error {
_, _, err := net.SplitHostPort(enc)
if err != nil {
return err
}
*chp = ConfigHostPort(enc)
return nil
}
// HostPort returns the host:port string held in chp.
func (chp ConfigHostPort) HostPort() string {
return string(chp)
}
// ConfigQueueSize can hold a queue size in a configuration struct.
type ConfigQueueSize uint
func (cqs *ConfigQueueSize) UnmarshalJSON(b []byte) error {
var enc uint
err := json.Unmarshal(b, &enc)
if err != nil {
return err
}
if enc == 0 {
return errors.New("queue size should be > 0")
}
*cqs = ConfigQueueSize(enc)
return nil
}
// QueueSize returns the queue size held in cqs.
func (cqs ConfigQueueSize) QueueSize() uint {
return uint(cqs)
}
// LoadFile reads a file possibly relative to a base dir.
func LoadFile(p, baseDir string) ([]byte, error) {
if p == "" {
return nil, nil
}
if !filepath.IsAbs(p) {
p = filepath.Join(baseDir, p)
}
return ioutil.ReadFile(p)
}
// used to implement getting config values with flag.Parse()
type val struct {
destField destField
accu map[string]json.RawMessage
}
func (v *val) String() string { // used to show default
return string(v.accu[v.destField.configName()])
}
func (v *val) IsBoolFlag() bool {
return v.destField.fld.Type.Kind() == reflect.Bool
}
func (v *val) marshalAsNeeded(s string) (json.RawMessage, error) {
var toMarshal interface{}
switch v.destField.dest.(type) {
case *string, FromString:
toMarshal = s
case *bool:
bit, err := strconv.ParseBool(s)
if err != nil {
return nil, err
}
toMarshal = bit
default:
return json.RawMessage(s), nil
}
return json.Marshal(toMarshal)
}
func (v *val) Set(s string) error {
marshalled, err := v.marshalAsNeeded(s)
if err != nil {
return err
}
v.accu[v.destField.configName()] = marshalled
return nil
}
func readOneConfig(accu map[string]json.RawMessage, cfgPath string) error {
r, err := os.Open(cfgPath)
if err != nil {
return err
}
defer r.Close()
err = json.NewDecoder(r).Decode(&accu)
if err != nil {
return err
}
return nil
}
// used to implement -cfg@=
type readConfigAtVal struct {
path string
accu map[string]json.RawMessage
}
func (v *readConfigAtVal) String() string {
return v.path
}
func (v *readConfigAtVal) Set(path string) error {
v.path = path
return readOneConfig(v.accu, path)
}
// readUsingFlags gets config values from command line flags.
func readUsingFlags(accu map[string]json.RawMessage, destValue reflect.Value) error {
if flag.Parsed() {
if IgnoreParsedFlags {
return nil
}
return fmt.Errorf("too late, flags already parsed")
}
destStruct := destValue.Elem()
for destField := range traverseStruct(destStruct) {
help := destField.fld.Tag.Get("help")
flag.Var(&val{destField, accu}, destField.configName(), help)
}
flag.Var(&readConfigAtVal{"<config.json>", accu}, "cfg@", "get config values from file")
flag.Parse()
return nil
}
// IgnoreParsedFlags will just have ReadFiles ignore <flags> if the
// command line was already parsed.
var IgnoreParsedFlags = false
// ReadFilesDefaults reads configuration from a set of files. The
// string "<flags>" can be used as a pseudo file-path, it will
// consider command line flags, invoking flag.Parse(). Among those the
// flag -cfg@=FILE can be used to get further config values from FILE.
// Defaults for fields can be given through a map[string]interface{}.
func ReadFilesDefaults(destConfig interface{}, defls map[string]interface{}, cfgFpaths ...string) error {
destValue, err := checkDestConfig("destConfig", destConfig)
if err != nil {
return err
}
// do the parsing in two phases for better error handling
p1 := make(map[string]json.RawMessage)
for field, value := range defls {
b, err := json.Marshal(value)
if err != nil {
return err
}
p1[field] = json.RawMessage(b)
}
readOne := false
for _, cfgPath := range cfgFpaths {
if cfgPath == "<flags>" {
err := readUsingFlags(p1, destValue)
if err != nil {
return err
}
readOne = true
continue
}
if _, err := os.Stat(cfgPath); err == nil {
err := readOneConfig(p1, cfgPath)
if err != nil {
return err
}
readOne = true
}
}
if !readOne {
return fmt.Errorf("no config to read")
}
return fillDestConfig(destValue, p1)
}
// ReadFiles reads configuration from a set of files exactly like
// ReadFilesDefaults but no defaults can be given making all fields
// mandatory.
func ReadFiles(destConfig interface{}, cfgFpaths ...string) error {
return ReadFilesDefaults(destConfig, nil, cfgFpaths...)
}
// CompareConfigs compares the two given configuration structures. It returns a list of differing fields or nil if the config contents are the same.
func CompareConfig(config1, config2 interface{}) ([]string, error) {
v1, err := checkDestConfig("config1", config1)
if err != nil {
return nil, err
}
v2, err := checkDestConfig("config2", config2)
if err != nil {
return nil, err
}
if v1.Type() != v2.Type() {
return nil, errors.New("config1 and config2 don't have the same type")
}
fields1 := traverseStruct(v1.Elem())
fields2 := traverseStruct(v2.Elem())
diff := make([]string, 0)
for {
d1 := <-fields1
d2 := <-fields2
if d1.dest == nil {
break
}
if !reflect.DeepEqual(d1.dest, d2.dest) {
diff = append(diff, d1.configName())
}
}
if len(diff) != 0 {
return diff, nil
}
return nil, nil
}
|