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
34 CrunchDispatchSlurmPath string
40 // NewLoader returns a new Loader with Stdin and Logger set to the
41 // given values, and all config paths set to their default values.
42 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
43 ldr := &Loader{Stdin: stdin, Logger: logger}
44 // Calling SetupFlags on a throwaway FlagSet has the side
45 // effect of assigning default values to the configurable
47 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
51 // SetupFlags configures a flagset so arguments like -config X can be
52 // used to change the loader's Path fields.
54 // ldr := NewLoader(os.Stdin, logrus.New())
55 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
56 // ldr.SetupFlags(flagset)
57 // // ldr.Path == "/etc/arvados/config.yml"
58 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
59 // // ldr.Path == "/tmp/c.yaml"
60 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
61 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
62 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
63 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
64 flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
65 flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
68 // MungeLegacyConfigArgs checks args for a -config flag whose argument
69 // is a regular file (or a symlink to one), but doesn't have a
70 // top-level "Clusters" key and therefore isn't a valid cluster
71 // configuration file. If it finds such a flag, it replaces -config
72 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
74 // This is used by programs that still need to accept "-config" as a
75 // way to specify a per-component config file until their config has
78 // If any errors are encountered while reading or parsing a config
79 // file, the given args are not munged. We presume the same errors
80 // will be encountered again and reported later on when trying to load
81 // cluster configuration from the same file, regardless of which
82 // struct we end up using.
83 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
84 munged := append([]string(nil), args...)
85 for i := 0; i < len(args); i++ {
86 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
90 if strings.Contains(args[i], "=") {
91 operand = strings.SplitN(args[i], "=", 2)[1]
92 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
98 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
101 f, err := os.Open(operand)
106 buf, err := ioutil.ReadAll(f)
110 var cfg arvados.Config
111 err = yaml.Unmarshal(buf, &cfg)
115 if len(cfg.Clusters) == 0 {
116 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
117 if operand == args[i] {
118 munged[i-1] = legacyConfigArg
120 munged[i] = legacyConfigArg + "=" + operand
125 // Disable legacy config loading for components other than the
126 // one that was specified
127 if legacyConfigArg != "-legacy-keepstore-config" {
128 ldr.KeepstorePath = ""
130 if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
131 ldr.CrunchDispatchSlurmPath = ""
133 if legacyConfigArg != "-legacy-ws-config" {
134 ldr.WebsocketPath = ""
140 func (ldr *Loader) loadBytes(path string) ([]byte, error) {
142 return ioutil.ReadAll(ldr.Stdin)
144 f, err := os.Open(path)
149 return ioutil.ReadAll(f)
152 func (ldr *Loader) Load() (*arvados.Config, error) {
153 if ldr.configdata == nil {
154 buf, err := ldr.loadBytes(ldr.Path)
161 // Load the config into a dummy map to get the cluster ID
162 // keys, discarding the values; then set up defaults for each
163 // cluster ID; then load the real config on top of the
166 Clusters map[string]struct{}
168 err := yaml.Unmarshal(ldr.configdata, &dummy)
172 if len(dummy.Clusters) == 0 {
173 return nil, ErrNoClustersDefined
176 // We can't merge deep structs here; instead, we unmarshal the
177 // default & loaded config files into generic maps, merge
178 // those, and then json-encode+decode the result into the
179 // config struct type.
180 var merged map[string]interface{}
181 for id := range dummy.Clusters {
182 var src map[string]interface{}
183 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
185 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
187 err = mergo.Merge(&merged, src, mergo.WithOverride)
189 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
192 var src map[string]interface{}
193 err = yaml.Unmarshal(ldr.configdata, &src)
195 return nil, fmt.Errorf("loading config data: %s", err)
197 ldr.logExtraKeys(merged, src, "")
198 removeSampleKeys(merged)
199 err = mergo.Merge(&merged, src, mergo.WithOverride)
201 return nil, fmt.Errorf("merging config data: %s", err)
204 // map[string]interface{} => json => arvados.Config
205 var cfg arvados.Config
209 errEnc = json.NewEncoder(pw).Encode(merged)
212 err = json.NewDecoder(pr).Decode(&cfg)
217 return nil, fmt.Errorf("transcoding config data: %s", err)
220 if !ldr.SkipDeprecated {
221 err = ldr.applyDeprecatedConfig(&cfg)
227 // legacy file is required when either:
228 // * a non-default location was specified
229 // * no primary config was loaded, and this is the
230 // legacy config file for the current component
231 for _, err := range []error{
232 ldr.loadOldKeepstoreConfig(&cfg),
233 ldr.loadOldCrunchDispatchSlurmConfig(&cfg),
234 ldr.loadOldWebsocketConfig(&cfg),
242 // Check for known mistakes
243 for id, cc := range cfg.Clusters {
244 err = checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection)
252 func checkKeyConflict(label string, m map[string]string) error {
253 saw := map[string]bool{}
255 k = strings.ToLower(k)
257 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
264 func removeSampleKeys(m map[string]interface{}) {
266 for _, v := range m {
267 if v, _ := v.(map[string]interface{}); v != nil {
273 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
274 if ldr.Logger == nil {
277 allowed := map[string]interface{}{}
278 for k, v := range expected {
279 allowed[strings.ToLower(k)] = v
281 for k, vsupp := range supplied {
283 // entry will be dropped in removeSampleKeys anyway
286 vexp, ok := allowed[strings.ToLower(k)]
287 if expected["SAMPLE"] != nil {
288 vexp = expected["SAMPLE"]
290 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s", prefix, k)
293 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
294 // if vsupp is a map but vexp isn't map, this
295 // will be caught elsewhere; see TestBadType.
297 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
298 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
300 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")