1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "github.com/ghodss/yaml"
23 "github.com/imdario/mergo"
24 "github.com/sirupsen/logrus"
27 //go:embed config.default.yml
28 var DefaultYAML []byte
30 var ErrNoClustersDefined = errors.New("config does not define any clusters")
34 Logger logrus.FieldLogger
35 SkipDeprecated bool // Don't load deprecated config keys
36 SkipLegacy bool // Don't load legacy config files
37 SkipAPICalls bool // Don't do checks that call RailsAPI/controller
42 CrunchDispatchSlurmPath string
46 KeepBalancePath string
51 // NewLoader returns a new Loader with Stdin and Logger set to the
52 // given values, and all config paths set to their default values.
53 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
54 ldr := &Loader{Stdin: stdin, Logger: logger}
55 // Calling SetupFlags on a throwaway FlagSet has the side
56 // effect of assigning default values to the configurable
58 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
62 // SetupFlags configures a flagset so arguments like -config X can be
63 // used to change the loader's Path fields.
65 // ldr := NewLoader(os.Stdin, logrus.New())
66 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
67 // ldr.SetupFlags(flagset)
68 // // ldr.Path == "/etc/arvados/config.yml"
69 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
70 // // ldr.Path == "/tmp/c.yaml"
71 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
72 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
74 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
75 flagset.StringVar(&ldr.KeepWebPath, "legacy-keepweb-config", defaultKeepWebConfigPath, "Legacy keep-web configuration `file`")
76 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
77 flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
78 flagset.StringVar(&ldr.KeepproxyPath, "legacy-keepproxy-config", defaultKeepproxyConfigPath, "Legacy keepproxy configuration `file`")
79 flagset.StringVar(&ldr.GitHttpdPath, "legacy-git-httpd-config", defaultGitHttpdConfigPath, "Legacy arv-git-httpd configuration `file`")
80 flagset.StringVar(&ldr.KeepBalancePath, "legacy-keepbalance-config", defaultKeepBalanceConfigPath, "Legacy keep-balance configuration `file`")
81 flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
85 // MungeLegacyConfigArgs checks args for a -config flag whose argument
86 // is a regular file (or a symlink to one), but doesn't have a
87 // top-level "Clusters" key and therefore isn't a valid cluster
88 // configuration file. If it finds such a flag, it replaces -config
89 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
91 // This is used by programs that still need to accept "-config" as a
92 // way to specify a per-component config file until their config has
95 // If any errors are encountered while reading or parsing a config
96 // file, the given args are not munged. We presume the same errors
97 // will be encountered again and reported later on when trying to load
98 // cluster configuration from the same file, regardless of which
99 // struct we end up using.
100 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
101 munged := append([]string(nil), args...)
102 for i := 0; i < len(args); i++ {
103 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
107 if strings.Contains(args[i], "=") {
108 operand = strings.SplitN(args[i], "=", 2)[1]
109 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
115 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
118 f, err := os.Open(operand)
123 buf, err := ioutil.ReadAll(f)
127 var cfg arvados.Config
128 err = yaml.Unmarshal(buf, &cfg)
132 if len(cfg.Clusters) == 0 {
133 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
134 if operand == args[i] {
135 munged[i-1] = legacyConfigArg
137 munged[i] = legacyConfigArg + "=" + operand
142 // Disable legacy config loading for components other than the
143 // one that was specified
144 if legacyConfigArg != "-legacy-keepstore-config" {
145 ldr.KeepstorePath = ""
147 if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
148 ldr.CrunchDispatchSlurmPath = ""
150 if legacyConfigArg != "-legacy-ws-config" {
151 ldr.WebsocketPath = ""
153 if legacyConfigArg != "-legacy-keepweb-config" {
156 if legacyConfigArg != "-legacy-keepproxy-config" {
157 ldr.KeepproxyPath = ""
159 if legacyConfigArg != "-legacy-git-httpd-config" {
160 ldr.GitHttpdPath = ""
162 if legacyConfigArg != "-legacy-keepbalance-config" {
163 ldr.KeepBalancePath = ""
169 func (ldr *Loader) loadBytes(path string) ([]byte, error) {
171 return ioutil.ReadAll(ldr.Stdin)
173 f, err := os.Open(path)
178 return ioutil.ReadAll(f)
181 func (ldr *Loader) Load() (*arvados.Config, error) {
182 if ldr.configdata == nil {
183 buf, err := ldr.loadBytes(ldr.Path)
190 // FIXME: We should reject YAML if the same key is used twice
191 // in a map/object, like {foo: bar, foo: baz}. Maybe we'll get
192 // this fixed free when we upgrade ghodss/yaml to a version
193 // that uses go-yaml v3.
195 // Load the config into a dummy map to get the cluster ID
196 // keys, discarding the values; then set up defaults for each
197 // cluster ID; then load the real config on top of the
200 Clusters map[string]struct{}
202 err := yaml.Unmarshal(ldr.configdata, &dummy)
206 if len(dummy.Clusters) == 0 {
207 return nil, ErrNoClustersDefined
210 // We can't merge deep structs here; instead, we unmarshal the
211 // default & loaded config files into generic maps, merge
212 // those, and then json-encode+decode the result into the
213 // config struct type.
214 var merged map[string]interface{}
215 for id := range dummy.Clusters {
216 var src map[string]interface{}
217 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
219 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
221 err = mergo.Merge(&merged, src, mergo.WithOverride)
223 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
226 var src map[string]interface{}
227 err = yaml.Unmarshal(ldr.configdata, &src)
229 return nil, fmt.Errorf("loading config data: %s", err)
231 ldr.logExtraKeys(merged, src, "")
232 removeSampleKeys(merged)
233 // We merge the loaded config into the default, overriding any existing keys.
234 // Make sure we do not override a default with a key that has a 'null' value.
236 err = mergo.Merge(&merged, src, mergo.WithOverride)
238 return nil, fmt.Errorf("merging config data: %s", err)
241 // map[string]interface{} => json => arvados.Config
242 var cfg arvados.Config
246 errEnc = json.NewEncoder(pw).Encode(merged)
249 err = json.NewDecoder(pr).Decode(&cfg)
254 return nil, fmt.Errorf("transcoding config data: %s", err)
257 var loadFuncs []func(*arvados.Config) error
258 if !ldr.SkipDeprecated {
259 loadFuncs = append(loadFuncs,
260 ldr.applyDeprecatedConfig,
261 ldr.applyDeprecatedVolumeDriverParameters,
265 // legacy file is required when either:
266 // * a non-default location was specified
267 // * no primary config was loaded, and this is the
268 // legacy config file for the current component
269 loadFuncs = append(loadFuncs,
270 ldr.loadOldEnvironmentVariables,
271 ldr.loadOldKeepstoreConfig,
272 ldr.loadOldKeepWebConfig,
273 ldr.loadOldCrunchDispatchSlurmConfig,
274 ldr.loadOldWebsocketConfig,
275 ldr.loadOldKeepproxyConfig,
276 ldr.loadOldGitHttpdConfig,
277 ldr.loadOldKeepBalanceConfig,
280 loadFuncs = append(loadFuncs, ldr.setImplicitStorageClasses)
281 for _, f := range loadFuncs {
288 // Preprocess/automate some configs
289 for id, cc := range cfg.Clusters {
290 ldr.autofillPreemptible("Clusters."+id, &cc)
292 if strings.Count(cc.Users.AnonymousUserToken, "/") == 3 {
293 // V2 token, strip it to just a secret
294 tmp := strings.Split(cc.Users.AnonymousUserToken, "/")
295 cc.Users.AnonymousUserToken = tmp[2]
298 cfg.Clusters[id] = cc
301 // Check for known mistakes
302 for id, cc := range cfg.Clusters {
303 for remote := range cc.RemoteClusters {
304 if remote == "*" || remote == "SAMPLE" {
307 err = ldr.checkClusterID(fmt.Sprintf("Clusters.%s.RemoteClusters.%s", id, remote), remote, true)
312 for _, err = range []error{
313 ldr.checkClusterID(fmt.Sprintf("Clusters.%s", id), id, false),
314 ldr.checkClusterID(fmt.Sprintf("Clusters.%s.Login.LoginCluster", id), cc.Login.LoginCluster, true),
315 ldr.checkToken(fmt.Sprintf("Clusters.%s.ManagementToken", id), cc.ManagementToken, true, false),
316 ldr.checkToken(fmt.Sprintf("Clusters.%s.SystemRootToken", id), cc.SystemRootToken, true, false),
317 ldr.checkToken(fmt.Sprintf("Clusters.%s.Users.AnonymousUserToken", id), cc.Users.AnonymousUserToken, false, true),
318 ldr.checkToken(fmt.Sprintf("Clusters.%s.Collections.BlobSigningKey", id), cc.Collections.BlobSigningKey, true, false),
319 checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection),
320 ldr.checkEnum("Containers.LocalKeepLogsToContainerLog", cc.Containers.LocalKeepLogsToContainerLog, "none", "all", "errors"),
321 ldr.checkEmptyKeepstores(cc),
322 ldr.checkUnlistedKeepstores(cc),
323 ldr.checkLocalKeepBlobBuffers(cc),
324 ldr.checkStorageClasses(cc),
325 ldr.checkCUDAVersions(cc),
326 // TODO: check non-empty Rendezvous on
327 // services other than Keepstore
337 var acceptableClusterIDRe = regexp.MustCompile(`^[a-z0-9]{5}$`)
339 func (ldr *Loader) checkClusterID(label, clusterID string, emptyStringOk bool) error {
340 if emptyStringOk && clusterID == "" {
342 } else if !acceptableClusterIDRe.MatchString(clusterID) {
343 return fmt.Errorf("%s: cluster ID should be 5 lowercase alphanumeric characters", label)
348 var acceptableTokenRe = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
349 var acceptableTokenLength = 32
351 func (ldr *Loader) checkToken(label, token string, mandatory bool, acceptV2 bool) error {
354 // when a token is not mandatory, the acceptable length and content is only checked if its length is non-zero
357 if ldr.Logger != nil {
358 ldr.Logger.Warnf("%s: secret token is not set (use %d+ random characters from a-z, A-Z, 0-9)", label, acceptableTokenLength)
361 } else if !acceptableTokenRe.MatchString(token) {
363 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
365 // Test for a proper V2 token
366 tmp := strings.SplitN(token, "/", 3)
368 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
370 if !strings.HasPrefix(token, "v2/") {
371 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
373 if !acceptableTokenRe.MatchString(tmp[2]) {
374 return fmt.Errorf("%s: unacceptable characters in V2 token secret (only a-z, A-Z, 0-9 are acceptable)", label)
376 if len(tmp[2]) < acceptableTokenLength {
377 ldr.Logger.Warnf("%s: secret is too short (should be at least %d characters)", label, acceptableTokenLength)
379 } else if len(token) < acceptableTokenLength {
380 if ldr.Logger != nil {
381 ldr.Logger.Warnf("%s: token is too short (should be at least %d characters)", label, acceptableTokenLength)
387 func (ldr *Loader) checkEnum(label, value string, accepted ...string) error {
388 for _, s := range accepted {
393 return fmt.Errorf("%s: unacceptable value %q: must be one of %q", label, value, accepted)
396 func (ldr *Loader) setImplicitStorageClasses(cfg *arvados.Config) error {
398 for id, cc := range cfg.Clusters {
399 if len(cc.StorageClasses) > 0 {
402 for _, vol := range cc.Volumes {
403 if len(vol.StorageClasses) > 0 {
407 // No explicit StorageClasses config info at all; fill
408 // in implicit defaults.
409 for id, vol := range cc.Volumes {
410 vol.StorageClasses = map[string]bool{"default": true}
413 cc.StorageClasses = map[string]arvados.StorageClassConfig{"default": {Default: true}}
414 cfg.Clusters[id] = cc
419 func (ldr *Loader) checkLocalKeepBlobBuffers(cc arvados.Cluster) error {
420 kbb := cc.Containers.LocalKeepBlobBuffersPerVCPU
424 for uuid, vol := range cc.Volumes {
425 if len(vol.AccessViaHosts) > 0 {
426 ldr.Logger.Warnf("LocalKeepBlobBuffersPerVCPU is %d but will not be used because at least one volume (%s) uses AccessViaHosts -- suggest changing to 0", kbb, uuid)
429 if !vol.ReadOnly && vol.Replication < cc.Collections.DefaultReplication {
430 ldr.Logger.Warnf("LocalKeepBlobBuffersPerVCPU is %d but will not be used because at least one volume (%s) has lower replication than DefaultReplication (%d < %d) -- suggest changing to 0", kbb, uuid, vol.Replication, cc.Collections.DefaultReplication)
437 func (ldr *Loader) checkStorageClasses(cc arvados.Cluster) error {
438 classOnVolume := map[string]bool{}
439 for volid, vol := range cc.Volumes {
440 if len(vol.StorageClasses) == 0 {
441 return fmt.Errorf("%s: volume has no StorageClasses listed", volid)
443 for classid := range vol.StorageClasses {
444 if _, ok := cc.StorageClasses[classid]; !ok {
445 return fmt.Errorf("%s: volume refers to storage class %q that is not defined in StorageClasses", volid, classid)
447 classOnVolume[classid] = true
451 for classid, sc := range cc.StorageClasses {
452 if !classOnVolume[classid] && len(cc.Volumes) > 0 {
453 ldr.Logger.Warnf("there are no volumes providing storage class %q", classid)
460 return fmt.Errorf("there is no default storage class (at least one entry in StorageClasses must have Default: true)")
465 func (ldr *Loader) checkCUDAVersions(cc arvados.Cluster) error {
466 for _, it := range cc.InstanceTypes {
467 if it.CUDA.DeviceCount == 0 {
471 _, err := strconv.ParseFloat(it.CUDA.DriverVersion, 64)
473 return fmt.Errorf("InstanceType %q has invalid CUDA.DriverVersion %q, expected format X.Y (%v)", it.Name, it.CUDA.DriverVersion, err)
475 _, err = strconv.ParseFloat(it.CUDA.HardwareCapability, 64)
477 return fmt.Errorf("InstanceType %q has invalid CUDA.HardwareCapability %q, expected format X.Y (%v)", it.Name, it.CUDA.HardwareCapability, err)
483 func checkKeyConflict(label string, m map[string]string) error {
484 saw := map[string]bool{}
486 k = strings.ToLower(k)
488 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
495 func removeNullKeys(m map[string]interface{}) {
496 for k, v := range m {
500 if v, _ := v.(map[string]interface{}); v != nil {
506 func removeSampleKeys(m map[string]interface{}) {
508 for _, v := range m {
509 if v, _ := v.(map[string]interface{}); v != nil {
515 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
516 if ldr.Logger == nil {
519 for k, vsupp := range supplied {
521 // entry will be dropped in removeSampleKeys anyway
524 vexp, ok := expected[k]
525 if expected["SAMPLE"] != nil {
526 // use the SAMPLE entry's keys as the
527 // "expected" map when checking vsupp
529 vexp = expected["SAMPLE"]
531 // check for a case-insensitive match
533 for ek := range expected {
534 if strings.EqualFold(k, ek) {
535 hint = " (perhaps you meant " + ek + "?)"
536 // If we don't delete this, it
537 // will end up getting merged,
539 // merging/overriding the
545 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s%s", prefix, k, hint)
548 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
549 // if vsupp is a map but vexp isn't map, this
550 // will be caught elsewhere; see TestBadType.
552 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
553 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
555 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
560 func (ldr *Loader) autofillPreemptible(label string, cc *arvados.Cluster) {
561 if factor := cc.Containers.PreemptiblePriceFactor; factor > 0 {
562 for name, it := range cc.InstanceTypes {
564 it.Preemptible = true
565 it.Price = it.Price * factor
566 it.Name = name + ".preemptible"
567 if it2, exists := cc.InstanceTypes[it.Name]; exists && it2 != it {
568 ldr.Logger.Warnf("%s.InstanceTypes[%s]: already exists, so not automatically adding a preemptible variant of %s", label, it.Name, name)
571 cc.InstanceTypes[it.Name] = it