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
33 CrunchDispatchSlurmPath string
39 // NewLoader returns a new Loader with Stdin and Logger set to the
40 // given values, and all config paths set to their default values.
41 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
42 ldr := &Loader{Stdin: stdin, Logger: logger}
43 // Calling SetupFlags on a throwaway FlagSet has the side
44 // effect of assigning default values to the configurable
46 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
50 // SetupFlags configures a flagset so arguments like -config X can be
51 // used to change the loader's Path fields.
53 // ldr := NewLoader(os.Stdin, logrus.New())
54 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
55 // ldr.SetupFlags(flagset)
56 // // ldr.Path == "/etc/arvados/config.yml"
57 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
58 // // ldr.Path == "/tmp/c.yaml"
59 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
60 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
61 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
62 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
63 flagset.StringVar(&ldr.WebsocketsPath, "legacy-ws-config", defaultWebsocketsConfigPath, "Legacy arvados-ws configuration `file`")
66 // MungeLegacyConfigArgs checks args for a -config flag whose argument
67 // is a regular file (or a symlink to one), but doesn't have a
68 // top-level "Clusters" key and therefore isn't a valid cluster
69 // configuration file. If it finds such a flag, it replaces -config
70 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
72 // This is used by programs that still need to accept "-config" as a
73 // way to specify a per-component config file until their config has
76 // If any errors are encountered while reading or parsing a config
77 // file, the given args are not munged. We presume the same errors
78 // will be encountered again and reported later on when trying to load
79 // cluster configuration from the same file, regardless of which
80 // struct we end up using.
81 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
82 munged := append([]string(nil), args...)
83 for i := 0; i < len(args); i++ {
84 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
88 if strings.Contains(args[i], "=") {
89 operand = strings.SplitN(args[i], "=", 2)[1]
90 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
96 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
99 f, err := os.Open(operand)
104 buf, err := ioutil.ReadAll(f)
108 var cfg arvados.Config
109 err = yaml.Unmarshal(buf, &cfg)
113 if len(cfg.Clusters) == 0 {
114 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
115 if operand == args[i] {
116 munged[i-1] = legacyConfigArg
118 munged[i] = legacyConfigArg + "=" + operand
125 func (ldr *Loader) loadBytes(path string) ([]byte, error) {
127 return ioutil.ReadAll(ldr.Stdin)
129 f, err := os.Open(path)
134 return ioutil.ReadAll(f)
137 func (ldr *Loader) LoadDefaults() (*arvados.Config, error) {
138 ldr.configdata = []byte(`Clusters: {zzzzz: {}}`)
139 defer func() { ldr.configdata = nil }()
143 func (ldr *Loader) Load() (*arvados.Config, error) {
144 if ldr.configdata == nil {
145 buf, err := ldr.loadBytes(ldr.Path)
152 // Load the config into a dummy map to get the cluster ID
153 // keys, discarding the values; then set up defaults for each
154 // cluster ID; then load the real config on top of the
157 Clusters map[string]struct{}
159 err := yaml.Unmarshal(ldr.configdata, &dummy)
163 if len(dummy.Clusters) == 0 {
164 return nil, ErrNoClustersDefined
167 // We can't merge deep structs here; instead, we unmarshal the
168 // default & loaded config files into generic maps, merge
169 // those, and then json-encode+decode the result into the
170 // config struct type.
171 var merged map[string]interface{}
172 for id := range dummy.Clusters {
173 var src map[string]interface{}
174 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
176 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
178 err = mergo.Merge(&merged, src, mergo.WithOverride)
180 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
183 var src map[string]interface{}
184 err = yaml.Unmarshal(ldr.configdata, &src)
186 return nil, fmt.Errorf("loading config data: %s", err)
188 ldr.logExtraKeys(merged, src, "")
189 removeSampleKeys(merged)
190 err = mergo.Merge(&merged, src, mergo.WithOverride)
192 return nil, fmt.Errorf("merging config data: %s", err)
195 // map[string]interface{} => json => arvados.Config
196 var cfg arvados.Config
200 errEnc = json.NewEncoder(pw).Encode(merged)
203 err = json.NewDecoder(pr).Decode(&cfg)
208 return nil, fmt.Errorf("transcoding config data: %s", err)
211 if !ldr.SkipDeprecated {
212 err = ldr.applyDeprecatedConfig(&cfg)
216 for _, err := range []error{
217 ldr.loadOldKeepstoreConfig(&cfg),
218 ldr.loadOldCrunchDispatchSlurmConfig(&cfg),
219 ldr.loadOldWebsocketsConfig(&cfg),
227 // Check for known mistakes
228 for id, cc := range cfg.Clusters {
229 err = checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection)
237 func checkKeyConflict(label string, m map[string]string) error {
238 saw := map[string]bool{}
240 k = strings.ToLower(k)
242 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
249 func removeSampleKeys(m map[string]interface{}) {
251 for _, v := range m {
252 if v, _ := v.(map[string]interface{}); v != nil {
258 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
259 if ldr.Logger == nil {
262 allowed := map[string]interface{}{}
263 for k, v := range expected {
264 allowed[strings.ToLower(k)] = v
266 for k, vsupp := range supplied {
268 // entry will be dropped in removeSampleKeys anyway
271 vexp, ok := allowed[strings.ToLower(k)]
272 if expected["SAMPLE"] != nil {
273 vexp = expected["SAMPLE"]
275 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s", prefix, k)
278 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
279 // if vsupp is a map but vexp isn't map, this
280 // will be caught elsewhere; see TestBadType.
282 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
283 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
285 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")