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
38 // NewLoader returns a new Loader with Stdin and Logger set to the
39 // given values, and all config paths set to their default values.
40 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
41 ldr := &Loader{Stdin: stdin, Logger: logger}
42 // Calling SetupFlags on a throwaway FlagSet has the side
43 // effect of assigning default values to the configurable
45 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
49 // SetupFlags configures a flagset so arguments like -config X can be
50 // used to change the loader's Path fields.
52 // ldr := NewLoader(os.Stdin, logrus.New())
53 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
54 // ldr.SetupFlags(flagset)
55 // // ldr.Path == "/etc/arvados/config.yml"
56 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
57 // // ldr.Path == "/tmp/c.yaml"
58 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
59 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
60 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
61 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
64 // MungeLegacyConfigArgs checks args for a -config flag whose argument
65 // is a regular file (or a symlink to one), but doesn't have a
66 // top-level "Clusters" key and therefore isn't a valid cluster
67 // configuration file. If it finds such a flag, it replaces -config
68 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
70 // This is used by programs that still need to accept "-config" as a
71 // way to specify a per-component config file until their config has
74 // If any errors are encountered while reading or parsing a config
75 // file, the given args are not munged. We presume the same errors
76 // will be encountered again and reported later on when trying to load
77 // cluster configuration from the same file, regardless of which
78 // struct we end up using.
79 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
80 munged := append([]string(nil), args...)
81 for i := 0; i < len(args); i++ {
82 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
86 if strings.Contains(args[i], "=") {
87 operand = strings.SplitN(args[i], "=", 2)[1]
88 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
94 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
97 f, err := os.Open(operand)
102 buf, err := ioutil.ReadAll(f)
106 var cfg arvados.Config
107 err = yaml.Unmarshal(buf, &cfg)
111 if len(cfg.Clusters) == 0 {
112 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
113 if operand == args[i] {
114 munged[i-1] = legacyConfigArg
116 munged[i] = legacyConfigArg + "=" + operand
123 func (ldr *Loader) loadBytes(path string) ([]byte, error) {
125 return ioutil.ReadAll(ldr.Stdin)
127 f, err := os.Open(path)
132 return ioutil.ReadAll(f)
135 func (ldr *Loader) Load() (*arvados.Config, error) {
136 if ldr.configdata == nil {
137 buf, err := ldr.loadBytes(ldr.Path)
144 // Load the config into a dummy map to get the cluster ID
145 // keys, discarding the values; then set up defaults for each
146 // cluster ID; then load the real config on top of the
149 Clusters map[string]struct{}
151 err := yaml.Unmarshal(ldr.configdata, &dummy)
155 if len(dummy.Clusters) == 0 {
156 return nil, ErrNoClustersDefined
159 // We can't merge deep structs here; instead, we unmarshal the
160 // default & loaded config files into generic maps, merge
161 // those, and then json-encode+decode the result into the
162 // config struct type.
163 var merged map[string]interface{}
164 for id := range dummy.Clusters {
165 var src map[string]interface{}
166 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
168 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
170 err = mergo.Merge(&merged, src, mergo.WithOverride)
172 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
175 var src map[string]interface{}
176 err = yaml.Unmarshal(ldr.configdata, &src)
178 return nil, fmt.Errorf("loading config data: %s", err)
180 ldr.logExtraKeys(merged, src, "")
181 removeSampleKeys(merged)
182 err = mergo.Merge(&merged, src, mergo.WithOverride)
184 return nil, fmt.Errorf("merging config data: %s", err)
187 // map[string]interface{} => json => arvados.Config
188 var cfg arvados.Config
192 errEnc = json.NewEncoder(pw).Encode(merged)
195 err = json.NewDecoder(pr).Decode(&cfg)
200 return nil, fmt.Errorf("transcoding config data: %s", err)
203 if !ldr.SkipDeprecated {
204 err = ldr.applyDeprecatedConfig(&cfg)
208 for _, err := range []error{
209 ldr.loadOldKeepstoreConfig(&cfg),
210 ldr.loadOldCrunchDispatchSlurmConfig(&cfg),
218 // Check for known mistakes
219 for id, cc := range cfg.Clusters {
220 err = checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection)
228 func checkKeyConflict(label string, m map[string]string) error {
229 saw := map[string]bool{}
231 k = strings.ToLower(k)
233 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
240 func removeSampleKeys(m map[string]interface{}) {
242 for _, v := range m {
243 if v, _ := v.(map[string]interface{}); v != nil {
249 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
250 if ldr.Logger == nil {
253 allowed := map[string]interface{}{}
254 for k, v := range expected {
255 allowed[strings.ToLower(k)] = v
257 for k, vsupp := range supplied {
259 // entry will be dropped in removeSampleKeys anyway
262 vexp, ok := allowed[strings.ToLower(k)]
263 if expected["SAMPLE"] != nil {
264 vexp = expected["SAMPLE"]
266 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s", prefix, k)
269 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
270 // if vsupp is a map but vexp isn't map, this
271 // will be caught elsewhere; see TestBadType.
273 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
274 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
276 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")