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
31 SkipAPICalls bool // Don't do checks that call RailsAPI/controller
36 CrunchDispatchSlurmPath string
44 // NewLoader returns a new Loader with Stdin and Logger set to the
45 // given values, and all config paths set to their default values.
46 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
47 ldr := &Loader{Stdin: stdin, Logger: logger}
48 // Calling SetupFlags on a throwaway FlagSet has the side
49 // effect of assigning default values to the configurable
51 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
55 // SetupFlags configures a flagset so arguments like -config X can be
56 // used to change the loader's Path fields.
58 // ldr := NewLoader(os.Stdin, logrus.New())
59 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
60 // ldr.SetupFlags(flagset)
61 // // ldr.Path == "/etc/arvados/config.yml"
62 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
63 // // ldr.Path == "/tmp/c.yaml"
64 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
65 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
66 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
67 flagset.StringVar(&ldr.KeepWebPath, "legacy-keepweb-config", defaultKeepWebConfigPath, "Legacy keep-web configuration `file`")
68 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
69 flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
70 flagset.StringVar(&ldr.KeepproxyPath, "legacy-keepproxy-config", defaultKeepproxyConfigPath, "Legacy keepproxy configuration `file`")
71 flagset.StringVar(&ldr.GitHttpdPath, "legacy-git-httpd-config", defaultGitHttpdConfigPath, "Legacy arv-git-httpd configuration `file`")
72 flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
75 // MungeLegacyConfigArgs checks args for a -config flag whose argument
76 // is a regular file (or a symlink to one), but doesn't have a
77 // top-level "Clusters" key and therefore isn't a valid cluster
78 // configuration file. If it finds such a flag, it replaces -config
79 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
81 // This is used by programs that still need to accept "-config" as a
82 // way to specify a per-component config file until their config has
85 // If any errors are encountered while reading or parsing a config
86 // file, the given args are not munged. We presume the same errors
87 // will be encountered again and reported later on when trying to load
88 // cluster configuration from the same file, regardless of which
89 // struct we end up using.
90 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
91 munged := append([]string(nil), args...)
92 for i := 0; i < len(args); i++ {
93 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
97 if strings.Contains(args[i], "=") {
98 operand = strings.SplitN(args[i], "=", 2)[1]
99 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
105 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
108 f, err := os.Open(operand)
113 buf, err := ioutil.ReadAll(f)
117 var cfg arvados.Config
118 err = yaml.Unmarshal(buf, &cfg)
122 if len(cfg.Clusters) == 0 {
123 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
124 if operand == args[i] {
125 munged[i-1] = legacyConfigArg
127 munged[i] = legacyConfigArg + "=" + operand
132 // Disable legacy config loading for components other than the
133 // one that was specified
134 if legacyConfigArg != "-legacy-keepstore-config" {
135 ldr.KeepstorePath = ""
137 if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
138 ldr.CrunchDispatchSlurmPath = ""
140 if legacyConfigArg != "-legacy-ws-config" {
141 ldr.WebsocketPath = ""
143 if legacyConfigArg != "-legacy-keepweb-config" {
146 if legacyConfigArg != "-legacy-keepproxy-config" {
147 ldr.KeepproxyPath = ""
149 if legacyConfigArg != "-legacy-git-httpd-config" {
150 ldr.GitHttpdPath = ""
156 func (ldr *Loader) loadBytes(path string) ([]byte, error) {
158 return ioutil.ReadAll(ldr.Stdin)
160 f, err := os.Open(path)
165 return ioutil.ReadAll(f)
168 func (ldr *Loader) Load() (*arvados.Config, error) {
169 if ldr.configdata == nil {
170 buf, err := ldr.loadBytes(ldr.Path)
177 // Load the config into a dummy map to get the cluster ID
178 // keys, discarding the values; then set up defaults for each
179 // cluster ID; then load the real config on top of the
182 Clusters map[string]struct{}
184 err := yaml.Unmarshal(ldr.configdata, &dummy)
188 if len(dummy.Clusters) == 0 {
189 return nil, ErrNoClustersDefined
192 // We can't merge deep structs here; instead, we unmarshal the
193 // default & loaded config files into generic maps, merge
194 // those, and then json-encode+decode the result into the
195 // config struct type.
196 var merged map[string]interface{}
197 for id := range dummy.Clusters {
198 var src map[string]interface{}
199 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
201 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
203 err = mergo.Merge(&merged, src, mergo.WithOverride)
205 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
208 var src map[string]interface{}
209 err = yaml.Unmarshal(ldr.configdata, &src)
211 return nil, fmt.Errorf("loading config data: %s", err)
213 ldr.logExtraKeys(merged, src, "")
214 removeSampleKeys(merged)
215 err = mergo.Merge(&merged, src, mergo.WithOverride)
217 return nil, fmt.Errorf("merging config data: %s", err)
220 // map[string]interface{} => json => arvados.Config
221 var cfg arvados.Config
225 errEnc = json.NewEncoder(pw).Encode(merged)
228 err = json.NewDecoder(pr).Decode(&cfg)
233 return nil, fmt.Errorf("transcoding config data: %s", err)
236 if !ldr.SkipDeprecated {
237 err = ldr.applyDeprecatedConfig(&cfg)
243 // legacy file is required when either:
244 // * a non-default location was specified
245 // * no primary config was loaded, and this is the
246 // legacy config file for the current component
247 for _, err := range []error{
248 ldr.loadOldKeepstoreConfig(&cfg),
249 ldr.loadOldKeepWebConfig(&cfg),
250 ldr.loadOldCrunchDispatchSlurmConfig(&cfg),
251 ldr.loadOldWebsocketConfig(&cfg),
252 ldr.loadOldKeepproxyConfig(&cfg),
253 ldr.loadOldGitHttpdConfig(&cfg),
261 // Check for known mistakes
262 for id, cc := range cfg.Clusters {
263 for _, err = range []error{
264 checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection),
265 ldr.checkEmptyKeepstores(cc),
266 ldr.checkUnlistedKeepstores(cc),
276 func checkKeyConflict(label string, m map[string]string) error {
277 saw := map[string]bool{}
279 k = strings.ToLower(k)
281 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
288 func removeSampleKeys(m map[string]interface{}) {
290 for _, v := range m {
291 if v, _ := v.(map[string]interface{}); v != nil {
297 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
298 if ldr.Logger == nil {
301 allowed := map[string]interface{}{}
302 for k, v := range expected {
303 allowed[strings.ToLower(k)] = v
305 for k, vsupp := range supplied {
307 // entry will be dropped in removeSampleKeys anyway
310 vexp, ok := allowed[strings.ToLower(k)]
311 if expected["SAMPLE"] != nil {
312 vexp = expected["SAMPLE"]
314 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s", prefix, k)
317 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
318 // if vsupp is a map but vexp isn't map, this
319 // will be caught elsewhere; see TestBadType.
321 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
322 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
324 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")