1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
18 "git.curoverse.com/arvados.git/sdk/go/arvados"
19 "github.com/ghodss/yaml"
20 "github.com/imdario/mergo"
21 "github.com/sirupsen/logrus"
24 var ErrNoClustersDefined = errors.New("config does not define any clusters")
28 Logger logrus.FieldLogger
29 SkipDeprecated bool // Don't load legacy/deprecated config keys/files
37 // NewLoader returns a new Loader with Stdin and Logger set to the
38 // given values, and all config paths set to their default values.
39 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
40 ldr := &Loader{Stdin: stdin, Logger: logger}
41 // Calling SetupFlags on a throwaway FlagSet has the side
42 // effect of assigning default values to the configurable
44 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
48 // SetupFlags configures a flagset so arguments like -config X can be
49 // used to change the loader's Path fields.
51 // ldr := NewLoader(os.Stdin, logrus.New())
52 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
53 // ldr.SetupFlags(flagset)
54 // // ldr.Path == "/etc/arvados/config.yml"
55 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
56 // // ldr.Path == "/tmp/c.yaml"
57 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
58 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
59 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
62 // MungeLegacyConfigArgs checks args for a -config flag whose argument
63 // is a regular file (or a symlink to one), but doesn't have a
64 // top-level "Clusters" key and therefore isn't a valid cluster
65 // configuration file. If it finds such a flag, it replaces -config
66 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
68 // This is used by programs that still need to accept "-config" as a
69 // way to specify a per-component config file until their config has
72 // If any errors are encountered while reading or parsing a config
73 // file, the given args are not munged. We presume the same errors
74 // will be encountered again and reported later on when trying to load
75 // cluster configuration from the same file, regardless of which
76 // struct we end up using.
77 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
78 munged := append([]string(nil), args...)
79 for i := 0; i < len(args); i++ {
80 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
84 if strings.Contains(args[i], "=") {
85 operand = strings.SplitN(args[i], "=", 2)[1]
86 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
92 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
95 f, err := os.Open(operand)
100 buf, err := ioutil.ReadAll(f)
104 var cfg arvados.Config
105 err = yaml.Unmarshal(buf, &cfg)
109 if len(cfg.Clusters) == 0 {
110 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
111 if operand == args[i] {
112 munged[i-1] = legacyConfigArg
114 munged[i] = legacyConfigArg + "=" + operand
121 func (ldr *Loader) loadBytes(path string) ([]byte, error) {
123 return ioutil.ReadAll(ldr.Stdin)
125 f, err := os.Open(path)
130 return ioutil.ReadAll(f)
133 func (ldr *Loader) Load() (*arvados.Config, error) {
134 if ldr.configdata == nil {
135 buf, err := ldr.loadBytes(ldr.Path)
142 // Load the config into a dummy map to get the cluster ID
143 // keys, discarding the values; then set up defaults for each
144 // cluster ID; then load the real config on top of the
147 Clusters map[string]struct{}
149 err := yaml.Unmarshal(ldr.configdata, &dummy)
153 if len(dummy.Clusters) == 0 {
154 return nil, ErrNoClustersDefined
157 // We can't merge deep structs here; instead, we unmarshal the
158 // default & loaded config files into generic maps, merge
159 // those, and then json-encode+decode the result into the
160 // config struct type.
161 var merged map[string]interface{}
162 for id := range dummy.Clusters {
163 var src map[string]interface{}
164 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
166 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
168 err = mergo.Merge(&merged, src, mergo.WithOverride)
170 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
173 var src map[string]interface{}
174 err = yaml.Unmarshal(ldr.configdata, &src)
176 return nil, fmt.Errorf("loading config data: %s", err)
178 ldr.logExtraKeys(merged, src, "")
179 removeSampleKeys(merged)
180 err = mergo.Merge(&merged, src, mergo.WithOverride)
182 return nil, fmt.Errorf("merging config data: %s", err)
185 // map[string]interface{} => json => arvados.Config
186 var cfg arvados.Config
190 errEnc = json.NewEncoder(pw).Encode(merged)
193 err = json.NewDecoder(pr).Decode(&cfg)
198 return nil, fmt.Errorf("transcoding config data: %s", err)
201 if !ldr.SkipDeprecated {
202 err = ldr.applyDeprecatedConfig(&cfg)
206 for _, err := range []error{
207 ldr.loadOldKeepstoreConfig(&cfg),
215 // Check for known mistakes
216 for id, cc := range cfg.Clusters {
217 err = checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection)
225 func checkKeyConflict(label string, m map[string]string) error {
226 saw := map[string]bool{}
228 k = strings.ToLower(k)
230 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
237 func removeSampleKeys(m map[string]interface{}) {
239 for _, v := range m {
240 if v, _ := v.(map[string]interface{}); v != nil {
246 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
247 if ldr.Logger == nil {
250 allowed := map[string]interface{}{}
251 for k, v := range expected {
252 allowed[strings.ToLower(k)] = v
254 for k, vsupp := range supplied {
255 vexp, ok := allowed[strings.ToLower(k)]
256 if !ok && expected["SAMPLE"] != nil {
257 vexp = expected["SAMPLE"]
259 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s", prefix, k)
262 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
263 // if vsupp is a map but vexp isn't map, this
264 // will be caught elsewhere; see TestBadType.
266 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
267 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
269 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")