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 deprecated config keys
30 SkipLegacy bool // Don't load legacy config files
35 CrunchDispatchSlurmPath string
41 // NewLoader returns a new Loader with Stdin and Logger set to the
42 // given values, and all config paths set to their default values.
43 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
44 ldr := &Loader{Stdin: stdin, Logger: logger}
45 // Calling SetupFlags on a throwaway FlagSet has the side
46 // effect of assigning default values to the configurable
48 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
52 // SetupFlags configures a flagset so arguments like -config X can be
53 // used to change the loader's Path fields.
55 // ldr := NewLoader(os.Stdin, logrus.New())
56 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
57 // ldr.SetupFlags(flagset)
58 // // ldr.Path == "/etc/arvados/config.yml"
59 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
60 // // ldr.Path == "/tmp/c.yaml"
61 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
62 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
63 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
64 flagset.StringVar(&ldr.KeepWebPath, "legacy-keepweb-config", defaultKeepWebConfigPath, "Legacy keep-web configuration `file`")
65 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
66 flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
67 flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
70 // MungeLegacyConfigArgs checks args for a -config flag whose argument
71 // is a regular file (or a symlink to one), but doesn't have a
72 // top-level "Clusters" key and therefore isn't a valid cluster
73 // configuration file. If it finds such a flag, it replaces -config
74 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
76 // This is used by programs that still need to accept "-config" as a
77 // way to specify a per-component config file until their config has
80 // If any errors are encountered while reading or parsing a config
81 // file, the given args are not munged. We presume the same errors
82 // will be encountered again and reported later on when trying to load
83 // cluster configuration from the same file, regardless of which
84 // struct we end up using.
85 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
86 munged := append([]string(nil), args...)
87 for i := 0; i < len(args); i++ {
88 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
92 if strings.Contains(args[i], "=") {
93 operand = strings.SplitN(args[i], "=", 2)[1]
94 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
100 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
103 f, err := os.Open(operand)
108 buf, err := ioutil.ReadAll(f)
112 var cfg arvados.Config
113 err = yaml.Unmarshal(buf, &cfg)
117 if len(cfg.Clusters) == 0 {
118 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
119 if operand == args[i] {
120 munged[i-1] = legacyConfigArg
122 munged[i] = legacyConfigArg + "=" + operand
127 // Disable legacy config loading for components other than the
128 // one that was specified
129 if legacyConfigArg != "-legacy-keepstore-config" {
130 ldr.KeepstorePath = ""
132 if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
133 ldr.CrunchDispatchSlurmPath = ""
135 if legacyConfigArg != "-legacy-ws-config" {
136 ldr.WebsocketPath = ""
142 func (ldr *Loader) loadBytes(path string) ([]byte, error) {
144 return ioutil.ReadAll(ldr.Stdin)
146 f, err := os.Open(path)
151 return ioutil.ReadAll(f)
154 func (ldr *Loader) LoadDefaults() (*arvados.Config, error) {
155 ldr.configdata = []byte(`Clusters: {zzzzz: {}}`)
156 defer func() { ldr.configdata = nil }()
160 func (ldr *Loader) Load() (*arvados.Config, error) {
161 if ldr.configdata == nil {
162 buf, err := ldr.loadBytes(ldr.Path)
169 // Load the config into a dummy map to get the cluster ID
170 // keys, discarding the values; then set up defaults for each
171 // cluster ID; then load the real config on top of the
174 Clusters map[string]struct{}
176 err := yaml.Unmarshal(ldr.configdata, &dummy)
180 if len(dummy.Clusters) == 0 {
181 return nil, ErrNoClustersDefined
184 // We can't merge deep structs here; instead, we unmarshal the
185 // default & loaded config files into generic maps, merge
186 // those, and then json-encode+decode the result into the
187 // config struct type.
188 var merged map[string]interface{}
189 for id := range dummy.Clusters {
190 var src map[string]interface{}
191 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
193 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
195 err = mergo.Merge(&merged, src, mergo.WithOverride)
197 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
200 var src map[string]interface{}
201 err = yaml.Unmarshal(ldr.configdata, &src)
203 return nil, fmt.Errorf("loading config data: %s", err)
205 ldr.logExtraKeys(merged, src, "")
206 removeSampleKeys(merged)
207 err = mergo.Merge(&merged, src, mergo.WithOverride)
209 return nil, fmt.Errorf("merging config data: %s", err)
212 // map[string]interface{} => json => arvados.Config
213 var cfg arvados.Config
217 errEnc = json.NewEncoder(pw).Encode(merged)
220 err = json.NewDecoder(pr).Decode(&cfg)
225 return nil, fmt.Errorf("transcoding config data: %s", err)
228 if !ldr.SkipDeprecated {
229 err = ldr.applyDeprecatedConfig(&cfg)
235 // legacy file is required when either:
236 // * a non-default location was specified
237 // * no primary config was loaded, and this is the
238 // legacy config file for the current component
239 for _, err := range []error{
240 ldr.loadOldKeepstoreConfig(&cfg),
241 ldr.loadOldKeepWebConfig(&cfg),
242 ldr.loadOldCrunchDispatchSlurmConfig(&cfg),
243 ldr.loadOldWebsocketConfig(&cfg),
251 // Check for known mistakes
252 for id, cc := range cfg.Clusters {
253 err = checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection)
261 func checkKeyConflict(label string, m map[string]string) error {
262 saw := map[string]bool{}
264 k = strings.ToLower(k)
266 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
273 func removeSampleKeys(m map[string]interface{}) {
275 for _, v := range m {
276 if v, _ := v.(map[string]interface{}); v != nil {
282 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
283 if ldr.Logger == nil {
286 allowed := map[string]interface{}{}
287 for k, v := range expected {
288 allowed[strings.ToLower(k)] = v
290 for k, vsupp := range supplied {
292 // entry will be dropped in removeSampleKeys anyway
295 vexp, ok := allowed[strings.ToLower(k)]
296 if expected["SAMPLE"] != nil {
297 vexp = expected["SAMPLE"]
299 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s", prefix, k)
302 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
303 // if vsupp is a map but vexp isn't map, this
304 // will be caught elsewhere; see TestBadType.
306 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
307 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
309 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")