| 1 |
/* |
| 2 |
Copyright 2013-2014 Canonical Ltd. |
| 3 |
|
| 4 |
This program is free software: you can redistribute it and/or modify it |
| 5 |
under the terms of the GNU General Public License version 3, as published |
| 6 |
by the Free Software Foundation. |
| 7 |
|
| 8 |
This program is distributed in the hope that it will be useful, but |
| 9 |
WITHOUT ANY WARRANTY; without even the implied warranties of |
| 10 |
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR |
| 11 |
PURPOSE. See the GNU General Public License for more details. |
| 12 |
|
| 13 |
You should have received a copy of the GNU General Public License along |
| 14 |
with this program. If not, see <http://www.gnu.org/licenses/>. |
| 15 |
*/ |
| 16 |
|
| 17 |
// Package config has helpers to parse and use JSON based configuration. |
| 18 |
package config |
| 19 |
|
| 20 |
import ( |
| 21 |
"encoding/json" |
| 22 |
"errors" |
| 23 |
"flag" |
| 24 |
"fmt" |
| 25 |
"io" |
| 26 |
"io/ioutil" |
| 27 |
"net" |
| 28 |
"os" |
| 29 |
"path/filepath" |
| 30 |
"reflect" |
| 31 |
"strconv" |
| 32 |
"strings" |
| 33 |
"time" |
| 34 |
) |
| 35 |
|
| 36 |
func checkDestConfig(name string, destConfig interface{}) (reflect.Value, error) { |
| 37 |
destValue := reflect.ValueOf(destConfig) |
| 38 |
if destValue.Kind() != reflect.Ptr || destValue.Elem().Kind() != reflect.Struct { |
| 39 |
return reflect.Value{}, fmt.Errorf("%s not *struct", name) |
| 40 |
} |
| 41 |
return destValue, nil |
| 42 |
} |
| 43 |
|
| 44 |
type destField struct { |
| 45 |
fld reflect.StructField |
| 46 |
dest interface{} |
| 47 |
} |
| 48 |
|
| 49 |
func (f destField) configName() string { |
| 50 |
fld := f.fld |
| 51 |
configName := strings.Split(fld.Tag.Get("json"), ",")[0] |
| 52 |
if configName == "" && fld.Name != "" { |
| 53 |
configName = strings.ToLower(fld.Name[:1]) + fld.Name[1:] |
| 54 |
} |
| 55 |
return configName |
| 56 |
} |
| 57 |
|
| 58 |
func traverseStruct(destStruct reflect.Value) <-chan destField { |
| 59 |
ch := make(chan destField) |
| 60 |
var traverse func(reflect.Value, chan<- destField) |
| 61 |
traverse = func(destStruct reflect.Value, ch chan<- destField) { |
| 62 |
structType := destStruct.Type() |
| 63 |
n := structType.NumField() |
| 64 |
for i := 0; i < n; i++ { |
| 65 |
fld := structType.Field(i) |
| 66 |
val := destStruct.Field(i) |
| 67 |
if fld.PkgPath != "" { // unexported |
| 68 |
continue |
| 69 |
} |
| 70 |
if fld.Anonymous { |
| 71 |
traverse(val, ch) |
| 72 |
continue |
| 73 |
} |
| 74 |
ch <- destField{ |
| 75 |
fld: fld, |
| 76 |
dest: val.Addr().Interface(), |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
go func() { |
| 81 |
traverse(destStruct, ch) |
| 82 |
close(ch) |
| 83 |
}() |
| 84 |
return ch |
| 85 |
} |
| 86 |
|
| 87 |
func fillDestConfig(destValue reflect.Value, p map[string]json.RawMessage) error { |
| 88 |
destStruct := destValue.Elem() |
| 89 |
for destField := range traverseStruct(destStruct) { |
| 90 |
configName := destField.configName() |
| 91 |
raw, found := p[configName] |
| 92 |
if !found { // assume all fields are mandatory for now |
| 93 |
return fmt.Errorf("missing %s", configName) |
| 94 |
} |
| 95 |
dest := destField.dest |
| 96 |
err := json.Unmarshal([]byte(raw), dest) |
| 97 |
if err != nil { |
| 98 |
return fmt.Errorf("%s: %v", configName, err) |
| 99 |
} |
| 100 |
} |
| 101 |
return nil |
| 102 |
} |
| 103 |
|
| 104 |
// ReadConfig reads a JSON configuration into destConfig which should |
| 105 |
// be a pointer to a structure. It does some more configuration |
| 106 |
// specific error checking than plain JSON decoding, and mentions |
| 107 |
// fields in errors. Configuration fields in the JSON object are |
| 108 |
// expected to start with lower case. |
| 109 |
func ReadConfig(r io.Reader, destConfig interface{}) error { |
| 110 |
destValue, err := checkDestConfig("destConfig", destConfig) |
| 111 |
if err != nil { |
| 112 |
return err |
| 113 |
} |
| 114 |
// do the parsing in two phases for better error handling |
| 115 |
var p1 map[string]json.RawMessage |
| 116 |
err = json.NewDecoder(r).Decode(&p1) |
| 117 |
if err != nil { |
| 118 |
return err |
| 119 |
} |
| 120 |
return fillDestConfig(destValue, p1) |
| 121 |
} |
| 122 |
|
| 123 |
// FromString are config holders that can be set by parsing a string. |
| 124 |
type FromString interface { |
| 125 |
SetFromString(enc string) error |
| 126 |
} |
| 127 |
|
| 128 |
// UnmarshalJSONViaString helps unmarshalling from JSON for FromString |
| 129 |
// supporting config holders. |
| 130 |
func UnmarshalJSONViaString(dest FromString, b []byte) error { |
| 131 |
var enc string |
| 132 |
err := json.Unmarshal(b, &enc) |
| 133 |
if err != nil { |
| 134 |
return err |
| 135 |
} |
| 136 |
return dest.SetFromString(enc) |
| 137 |
} |
| 138 |
|
| 139 |
// ConfigTimeDuration can hold a time.Duration in a configuration struct, |
| 140 |
// that is parsed from a string as supported by time.ParseDuration. |
| 141 |
type ConfigTimeDuration struct { |
| 142 |
time.Duration |
| 143 |
} |
| 144 |
|
| 145 |
func (ctd *ConfigTimeDuration) UnmarshalJSON(b []byte) error { |
| 146 |
return UnmarshalJSONViaString(ctd, b) |
| 147 |
} |
| 148 |
|
| 149 |
func (ctd *ConfigTimeDuration) SetFromString(enc string) error { |
| 150 |
v, err := time.ParseDuration(enc) |
| 151 |
if err != nil { |
| 152 |
return err |
| 153 |
} |
| 154 |
*ctd = ConfigTimeDuration{v} |
| 155 |
return nil |
| 156 |
} |
| 157 |
|
| 158 |
// TimeDuration returns the time.Duration held in ctd. |
| 159 |
func (ctd ConfigTimeDuration) TimeDuration() time.Duration { |
| 160 |
return ctd.Duration |
| 161 |
} |
| 162 |
|
| 163 |
// ConfigHostPort can hold a host:port string in a configuration struct. |
| 164 |
type ConfigHostPort string |
| 165 |
|
| 166 |
func (chp *ConfigHostPort) UnmarshalJSON(b []byte) error { |
| 167 |
return UnmarshalJSONViaString(chp, b) |
| 168 |
} |
| 169 |
|
| 170 |
func (chp *ConfigHostPort) SetFromString(enc string) error { |
| 171 |
_, _, err := net.SplitHostPort(enc) |
| 172 |
if err != nil { |
| 173 |
return err |
| 174 |
} |
| 175 |
*chp = ConfigHostPort(enc) |
| 176 |
return nil |
| 177 |
} |
| 178 |
|
| 179 |
// HostPort returns the host:port string held in chp. |
| 180 |
func (chp ConfigHostPort) HostPort() string { |
| 181 |
return string(chp) |
| 182 |
} |
| 183 |
|
| 184 |
// ConfigQueueSize can hold a queue size in a configuration struct. |
| 185 |
type ConfigQueueSize uint |
| 186 |
|
| 187 |
func (cqs *ConfigQueueSize) UnmarshalJSON(b []byte) error { |
| 188 |
var enc uint |
| 189 |
err := json.Unmarshal(b, &enc) |
| 190 |
if err != nil { |
| 191 |
return err |
| 192 |
} |
| 193 |
if enc == 0 { |
| 194 |
return errors.New("queue size should be > 0") |
| 195 |
} |
| 196 |
*cqs = ConfigQueueSize(enc) |
| 197 |
return nil |
| 198 |
} |
| 199 |
|
| 200 |
// QueueSize returns the queue size held in cqs. |
| 201 |
func (cqs ConfigQueueSize) QueueSize() uint { |
| 202 |
return uint(cqs) |
| 203 |
} |
| 204 |
|
| 205 |
// LoadFile reads a file possibly relative to a base dir. |
| 206 |
func LoadFile(p, baseDir string) ([]byte, error) { |
| 207 |
if p == "" { |
| 208 |
return nil, nil |
| 209 |
} |
| 210 |
if !filepath.IsAbs(p) { |
| 211 |
p = filepath.Join(baseDir, p) |
| 212 |
} |
| 213 |
return ioutil.ReadFile(p) |
| 214 |
} |
| 215 |
|
| 216 |
// used to implement getting config values with flag.Parse() |
| 217 |
type val struct { |
| 218 |
destField destField |
| 219 |
accu map[string]json.RawMessage |
| 220 |
} |
| 221 |
|
| 222 |
func (v *val) String() string { // used to show default |
| 223 |
return string(v.accu[v.destField.configName()]) |
| 224 |
} |
| 225 |
|
| 226 |
func (v *val) IsBoolFlag() bool { |
| 227 |
return v.destField.fld.Type.Kind() == reflect.Bool |
| 228 |
} |
| 229 |
|
| 230 |
func (v *val) marshalAsNeeded(s string) (json.RawMessage, error) { |
| 231 |
var toMarshal interface{} |
| 232 |
switch v.destField.dest.(type) { |
| 233 |
case *string, FromString: |
| 234 |
toMarshal = s |
| 235 |
case *bool: |
| 236 |
bit, err := strconv.ParseBool(s) |
| 237 |
if err != nil { |
| 238 |
return nil, err |
| 239 |
} |
| 240 |
toMarshal = bit |
| 241 |
default: |
| 242 |
return json.RawMessage(s), nil |
| 243 |
} |
| 244 |
return json.Marshal(toMarshal) |
| 245 |
} |
| 246 |
|
| 247 |
func (v *val) Set(s string) error { |
| 248 |
marshalled, err := v.marshalAsNeeded(s) |
| 249 |
if err != nil { |
| 250 |
return err |
| 251 |
} |
| 252 |
v.accu[v.destField.configName()] = marshalled |
| 253 |
return nil |
| 254 |
} |
| 255 |
|
| 256 |
func readOneConfig(accu map[string]json.RawMessage, cfgPath string) error { |
| 257 |
r, err := os.Open(cfgPath) |
| 258 |
if err != nil { |
| 259 |
return err |
| 260 |
} |
| 261 |
defer r.Close() |
| 262 |
err = json.NewDecoder(r).Decode(&accu) |
| 263 |
if err != nil { |
| 264 |
return err |
| 265 |
} |
| 266 |
return nil |
| 267 |
} |
| 268 |
|
| 269 |
// used to implement -cfg@= |
| 270 |
type readConfigAtVal struct { |
| 271 |
path string |
| 272 |
accu map[string]json.RawMessage |
| 273 |
} |
| 274 |
|
| 275 |
func (v *readConfigAtVal) String() string { |
| 276 |
return v.path |
| 277 |
} |
| 278 |
|
| 279 |
func (v *readConfigAtVal) Set(path string) error { |
| 280 |
v.path = path |
| 281 |
return readOneConfig(v.accu, path) |
| 282 |
} |
| 283 |
|
| 284 |
// readUsingFlags gets config values from command line flags. |
| 285 |
func readUsingFlags(accu map[string]json.RawMessage, destValue reflect.Value) error { |
| 286 |
if flag.Parsed() { |
| 287 |
if IgnoreParsedFlags { |
| 288 |
return nil |
| 289 |
} |
| 290 |
return fmt.Errorf("too late, flags already parsed") |
| 291 |
} |
| 292 |
destStruct := destValue.Elem() |
| 293 |
for destField := range traverseStruct(destStruct) { |
| 294 |
help := destField.fld.Tag.Get("help") |
| 295 |
flag.Var(&val{destField, accu}, destField.configName(), help) |
| 296 |
} |
| 297 |
flag.Var(&readConfigAtVal{"<config.json>", accu}, "cfg@", "get config values from file") |
| 298 |
flag.Parse() |
| 299 |
return nil |
| 300 |
} |
| 301 |
|
| 302 |
// IgnoreParsedFlags will just have ReadFiles ignore <flags> if the |
| 303 |
// command line was already parsed. |
| 304 |
var IgnoreParsedFlags = false |
| 305 |
|
| 306 |
// ReadFilesDefaults reads configuration from a set of files. The |
| 307 |
// string "<flags>" can be used as a pseudo file-path, it will |
| 308 |
// consider command line flags, invoking flag.Parse(). Among those the |
| 309 |
// flag -cfg@=FILE can be used to get further config values from FILE. |
| 310 |
// Defaults for fields can be given through a map[string]interface{}. |
| 311 |
func ReadFilesDefaults(destConfig interface{}, defls map[string]interface{}, cfgFpaths ...string) error { |
| 312 |
destValue, err := checkDestConfig("destConfig", destConfig) |
| 313 |
if err != nil { |
| 314 |
return err |
| 315 |
} |
| 316 |
// do the parsing in two phases for better error handling |
| 317 |
p1 := make(map[string]json.RawMessage) |
| 318 |
for field, value := range defls { |
| 319 |
b, err := json.Marshal(value) |
| 320 |
if err != nil { |
| 321 |
return err |
| 322 |
} |
| 323 |
p1[field] = json.RawMessage(b) |
| 324 |
} |
| 325 |
readOne := false |
| 326 |
for _, cfgPath := range cfgFpaths { |
| 327 |
if cfgPath == "<flags>" { |
| 328 |
err := readUsingFlags(p1, destValue) |
| 329 |
if err != nil { |
| 330 |
return err |
| 331 |
} |
| 332 |
readOne = true |
| 333 |
continue |
| 334 |
} |
| 335 |
if _, err := os.Stat(cfgPath); err == nil { |
| 336 |
err := readOneConfig(p1, cfgPath) |
| 337 |
if err != nil { |
| 338 |
return err |
| 339 |
} |
| 340 |
readOne = true |
| 341 |
} |
| 342 |
} |
| 343 |
if !readOne { |
| 344 |
return fmt.Errorf("no config to read") |
| 345 |
} |
| 346 |
return fillDestConfig(destValue, p1) |
| 347 |
} |
| 348 |
|
| 349 |
// ReadFiles reads configuration from a set of files exactly like |
| 350 |
// ReadFilesDefaults but no defaults can be given making all fields |
| 351 |
// mandatory. |
| 352 |
func ReadFiles(destConfig interface{}, cfgFpaths ...string) error { |
| 353 |
return ReadFilesDefaults(destConfig, nil, cfgFpaths...) |
| 354 |
} |
| 355 |
|
| 356 |
// CompareConfigs compares the two given configuration structures. It returns a list of differing fields or nil if the config contents are the same. |
| 357 |
func CompareConfig(config1, config2 interface{}) ([]string, error) { |
| 358 |
v1, err := checkDestConfig("config1", config1) |
| 359 |
if err != nil { |
| 360 |
return nil, err |
| 361 |
} |
| 362 |
v2, err := checkDestConfig("config2", config2) |
| 363 |
if err != nil { |
| 364 |
return nil, err |
| 365 |
} |
| 366 |
if v1.Type() != v2.Type() { |
| 367 |
return nil, errors.New("config1 and config2 don't have the same type") |
| 368 |
} |
| 369 |
fields1 := traverseStruct(v1.Elem()) |
| 370 |
fields2 := traverseStruct(v2.Elem()) |
| 371 |
diff := make([]string, 0) |
| 372 |
for { |
| 373 |
d1 := <-fields1 |
| 374 |
d2 := <-fields2 |
| 375 |
if d1.dest == nil { |
| 376 |
break |
| 377 |
} |
| 378 |
if !reflect.DeepEqual(d1.dest, d2.dest) { |
| 379 |
diff = append(diff, d1.configName()) |
| 380 |
} |
| 381 |
} |
| 382 |
if len(diff) != 0 { |
| 383 |
return diff, nil |
| 384 |
} |
| 385 |
return nil, nil |
| 386 |
} |