1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.arvados.org/arvados.git/sdk/go/arvados"
24 "github.com/ghodss/yaml"
25 "github.com/imdario/mergo"
26 "github.com/prometheus/client_golang/prometheus"
27 "github.com/sirupsen/logrus"
30 //go:embed config.default.yml
31 var DefaultYAML []byte
33 var ErrNoClustersDefined = errors.New("config does not define any clusters")
37 Logger logrus.FieldLogger
38 SkipDeprecated bool // Don't load deprecated config keys
39 SkipLegacy bool // Don't load legacy config files
40 SkipAPICalls bool // Don't do checks that call RailsAPI/controller
45 CrunchDispatchSlurmPath string
49 KeepBalancePath string
52 // UTC time for configdata: either the modtime of the file we
53 // read configdata from, or the time when we read configdata
55 sourceTimestamp time.Time
56 // UTC time when configdata was read.
57 loadTimestamp time.Time
60 // NewLoader returns a new Loader with Stdin and Logger set to the
61 // given values, and all config paths set to their default values.
62 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
63 ldr := &Loader{Stdin: stdin, Logger: logger}
64 // Calling SetupFlags on a throwaway FlagSet has the side
65 // effect of assigning default values to the configurable
67 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
71 // SetupFlags configures a flagset so arguments like -config X can be
72 // used to change the loader's Path fields.
74 // ldr := NewLoader(os.Stdin, logrus.New())
75 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
76 // ldr.SetupFlags(flagset)
77 // // ldr.Path == "/etc/arvados/config.yml"
78 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
79 // // ldr.Path == "/tmp/c.yaml"
80 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
81 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
83 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
84 flagset.StringVar(&ldr.KeepWebPath, "legacy-keepweb-config", defaultKeepWebConfigPath, "Legacy keep-web configuration `file`")
85 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
86 flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
87 flagset.StringVar(&ldr.KeepproxyPath, "legacy-keepproxy-config", defaultKeepproxyConfigPath, "Legacy keepproxy configuration `file`")
88 flagset.StringVar(&ldr.GitHttpdPath, "legacy-git-httpd-config", defaultGitHttpdConfigPath, "Legacy arvados-git-httpd configuration `file`")
89 flagset.StringVar(&ldr.KeepBalancePath, "legacy-keepbalance-config", defaultKeepBalanceConfigPath, "Legacy keep-balance configuration `file`")
90 flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
94 // MungeLegacyConfigArgs checks args for a -config flag whose argument
95 // is a regular file (or a symlink to one), but doesn't have a
96 // top-level "Clusters" key and therefore isn't a valid cluster
97 // configuration file. If it finds such a flag, it replaces -config
98 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
100 // This is used by programs that still need to accept "-config" as a
101 // way to specify a per-component config file until their config has
104 // If any errors are encountered while reading or parsing a config
105 // file, the given args are not munged. We presume the same errors
106 // will be encountered again and reported later on when trying to load
107 // cluster configuration from the same file, regardless of which
108 // struct we end up using.
109 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
110 munged := append([]string(nil), args...)
111 for i := 0; i < len(args); i++ {
112 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
116 if strings.Contains(args[i], "=") {
117 operand = strings.SplitN(args[i], "=", 2)[1]
118 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
124 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
127 f, err := os.Open(operand)
132 buf, err := ioutil.ReadAll(f)
136 var cfg arvados.Config
137 err = yaml.Unmarshal(buf, &cfg)
141 if len(cfg.Clusters) == 0 {
142 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
143 if operand == args[i] {
144 munged[i-1] = legacyConfigArg
146 munged[i] = legacyConfigArg + "=" + operand
151 // Disable legacy config loading for components other than the
152 // one that was specified
153 if legacyConfigArg != "-legacy-keepstore-config" {
154 ldr.KeepstorePath = ""
156 if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
157 ldr.CrunchDispatchSlurmPath = ""
159 if legacyConfigArg != "-legacy-ws-config" {
160 ldr.WebsocketPath = ""
162 if legacyConfigArg != "-legacy-keepweb-config" {
165 if legacyConfigArg != "-legacy-keepproxy-config" {
166 ldr.KeepproxyPath = ""
168 if legacyConfigArg != "-legacy-git-httpd-config" {
169 ldr.GitHttpdPath = ""
171 if legacyConfigArg != "-legacy-keepbalance-config" {
172 ldr.KeepBalancePath = ""
178 func (ldr *Loader) loadBytes(path string) (buf []byte, sourceTime, loadTime time.Time, err error) {
179 loadTime = time.Now().UTC()
181 buf, err = ioutil.ReadAll(ldr.Stdin)
182 sourceTime = loadTime
185 f, err := os.Open(path)
194 sourceTime = fi.ModTime().UTC()
195 buf, err = ioutil.ReadAll(f)
199 func (ldr *Loader) Load() (*arvados.Config, error) {
200 if ldr.configdata == nil {
201 buf, sourceTime, loadTime, err := ldr.loadBytes(ldr.Path)
206 ldr.sourceTimestamp = sourceTime
207 ldr.loadTimestamp = loadTime
210 // FIXME: We should reject YAML if the same key is used twice
211 // in a map/object, like {foo: bar, foo: baz}. Maybe we'll get
212 // this fixed free when we upgrade ghodss/yaml to a version
213 // that uses go-yaml v3.
215 // Load the config into a dummy map to get the cluster ID
216 // keys, discarding the values; then set up defaults for each
217 // cluster ID; then load the real config on top of the
220 Clusters map[string]struct{}
222 err := yaml.Unmarshal(ldr.configdata, &dummy)
226 if len(dummy.Clusters) == 0 {
227 return nil, ErrNoClustersDefined
230 // We can't merge deep structs here; instead, we unmarshal the
231 // default & loaded config files into generic maps, merge
232 // those, and then json-encode+decode the result into the
233 // config struct type.
234 var merged map[string]interface{}
235 for id := range dummy.Clusters {
236 var src map[string]interface{}
237 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
239 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
241 err = mergo.Merge(&merged, src, mergo.WithOverride)
243 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
246 var src map[string]interface{}
247 err = yaml.Unmarshal(ldr.configdata, &src)
249 return nil, fmt.Errorf("loading config data: %s", err)
251 ldr.logExtraKeys(merged, src, "")
252 removeSampleKeys(merged)
253 // We merge the loaded config into the default, overriding any existing keys.
254 // Make sure we do not override a default with a key that has a 'null' value.
256 err = mergo.Merge(&merged, src, mergo.WithOverride)
258 return nil, fmt.Errorf("merging config data: %s", err)
261 // map[string]interface{} => json => arvados.Config
262 var cfg arvados.Config
266 errEnc = json.NewEncoder(pw).Encode(merged)
269 err = json.NewDecoder(pr).Decode(&cfg)
274 return nil, fmt.Errorf("transcoding config data: %s", err)
277 var loadFuncs []func(*arvados.Config) error
278 if !ldr.SkipDeprecated {
279 loadFuncs = append(loadFuncs,
280 ldr.applyDeprecatedConfig,
281 ldr.applyDeprecatedVolumeDriverParameters,
285 // legacy file is required when either:
286 // * a non-default location was specified
287 // * no primary config was loaded, and this is the
288 // legacy config file for the current component
289 loadFuncs = append(loadFuncs,
290 ldr.loadOldEnvironmentVariables,
291 ldr.loadOldKeepstoreConfig,
292 ldr.loadOldKeepWebConfig,
293 ldr.loadOldCrunchDispatchSlurmConfig,
294 ldr.loadOldWebsocketConfig,
295 ldr.loadOldKeepproxyConfig,
296 ldr.loadOldGitHttpdConfig,
297 ldr.loadOldKeepBalanceConfig,
300 loadFuncs = append(loadFuncs, ldr.setImplicitStorageClasses)
301 for _, f := range loadFuncs {
308 // Preprocess/automate some configs
309 for id, cc := range cfg.Clusters {
310 ldr.autofillPreemptible("Clusters."+id, &cc)
312 if strings.Count(cc.Users.AnonymousUserToken, "/") == 3 {
313 // V2 token, strip it to just a secret
314 tmp := strings.Split(cc.Users.AnonymousUserToken, "/")
315 cc.Users.AnonymousUserToken = tmp[2]
318 cfg.Clusters[id] = cc
321 // Check for known mistakes
322 for id, cc := range cfg.Clusters {
323 for remote := range cc.RemoteClusters {
324 if remote == "*" || remote == "SAMPLE" {
327 err = ldr.checkClusterID(fmt.Sprintf("Clusters.%s.RemoteClusters.%s", id, remote), remote, true)
332 for _, err = range []error{
333 ldr.checkClusterID(fmt.Sprintf("Clusters.%s", id), id, false),
334 ldr.checkClusterID(fmt.Sprintf("Clusters.%s.Login.LoginCluster", id), cc.Login.LoginCluster, true),
335 ldr.checkToken(fmt.Sprintf("Clusters.%s.ManagementToken", id), cc.ManagementToken, true, false),
336 ldr.checkToken(fmt.Sprintf("Clusters.%s.SystemRootToken", id), cc.SystemRootToken, true, false),
337 ldr.checkToken(fmt.Sprintf("Clusters.%s.Users.AnonymousUserToken", id), cc.Users.AnonymousUserToken, false, true),
338 ldr.checkToken(fmt.Sprintf("Clusters.%s.Collections.BlobSigningKey", id), cc.Collections.BlobSigningKey, true, false),
339 checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection),
340 ldr.checkEnum("Containers.LocalKeepLogsToContainerLog", cc.Containers.LocalKeepLogsToContainerLog, "none", "all", "errors"),
341 ldr.checkEmptyKeepstores(cc),
342 ldr.checkUnlistedKeepstores(cc),
343 ldr.checkLocalKeepBlobBuffers(cc),
344 ldr.checkStorageClasses(cc),
345 ldr.checkCUDAVersions(cc),
346 // TODO: check non-empty Rendezvous on
347 // services other than Keepstore
354 cfg.SourceTimestamp = ldr.sourceTimestamp
355 cfg.SourceSHA256 = fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
359 var acceptableClusterIDRe = regexp.MustCompile(`^[a-z0-9]{5}$`)
361 func (ldr *Loader) checkClusterID(label, clusterID string, emptyStringOk bool) error {
362 if emptyStringOk && clusterID == "" {
364 } else if !acceptableClusterIDRe.MatchString(clusterID) {
365 return fmt.Errorf("%s: cluster ID should be 5 alphanumeric characters", label)
370 var acceptableTokenRe = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
371 var acceptableTokenLength = 32
373 func (ldr *Loader) checkToken(label, token string, mandatory bool, acceptV2 bool) error {
376 // when a token is not mandatory, the acceptable length and content is only checked if its length is non-zero
379 if ldr.Logger != nil {
380 ldr.Logger.Warnf("%s: secret token is not set (use %d+ random characters from a-z, A-Z, 0-9)", label, acceptableTokenLength)
383 } else if !acceptableTokenRe.MatchString(token) {
385 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
387 // Test for a proper V2 token
388 tmp := strings.SplitN(token, "/", 3)
390 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
392 if !strings.HasPrefix(token, "v2/") {
393 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
395 if !acceptableTokenRe.MatchString(tmp[2]) {
396 return fmt.Errorf("%s: unacceptable characters in V2 token secret (only a-z, A-Z, 0-9 are acceptable)", label)
398 if len(tmp[2]) < acceptableTokenLength {
399 ldr.Logger.Warnf("%s: secret is too short (should be at least %d characters)", label, acceptableTokenLength)
401 } else if len(token) < acceptableTokenLength {
402 if ldr.Logger != nil {
403 ldr.Logger.Warnf("%s: token is too short (should be at least %d characters)", label, acceptableTokenLength)
409 func (ldr *Loader) checkEnum(label, value string, accepted ...string) error {
410 for _, s := range accepted {
415 return fmt.Errorf("%s: unacceptable value %q: must be one of %q", label, value, accepted)
418 func (ldr *Loader) setImplicitStorageClasses(cfg *arvados.Config) error {
420 for id, cc := range cfg.Clusters {
421 if len(cc.StorageClasses) > 0 {
424 for _, vol := range cc.Volumes {
425 if len(vol.StorageClasses) > 0 {
429 // No explicit StorageClasses config info at all; fill
430 // in implicit defaults.
431 for id, vol := range cc.Volumes {
432 vol.StorageClasses = map[string]bool{"default": true}
435 cc.StorageClasses = map[string]arvados.StorageClassConfig{"default": {Default: true}}
436 cfg.Clusters[id] = cc
441 func (ldr *Loader) checkLocalKeepBlobBuffers(cc arvados.Cluster) error {
442 kbb := cc.Containers.LocalKeepBlobBuffersPerVCPU
446 for uuid, vol := range cc.Volumes {
447 if len(vol.AccessViaHosts) > 0 {
448 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)
451 if !vol.ReadOnly && vol.Replication < cc.Collections.DefaultReplication {
452 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)
459 func (ldr *Loader) checkStorageClasses(cc arvados.Cluster) error {
460 classOnVolume := map[string]bool{}
461 for volid, vol := range cc.Volumes {
462 if len(vol.StorageClasses) == 0 {
463 return fmt.Errorf("%s: volume has no StorageClasses listed", volid)
465 for classid := range vol.StorageClasses {
466 if _, ok := cc.StorageClasses[classid]; !ok {
467 return fmt.Errorf("%s: volume refers to storage class %q that is not defined in StorageClasses", volid, classid)
469 classOnVolume[classid] = true
473 for classid, sc := range cc.StorageClasses {
474 if !classOnVolume[classid] && len(cc.Volumes) > 0 {
475 ldr.Logger.Warnf("there are no volumes providing storage class %q", classid)
482 return fmt.Errorf("there is no default storage class (at least one entry in StorageClasses must have Default: true)")
487 func (ldr *Loader) checkCUDAVersions(cc arvados.Cluster) error {
488 for _, it := range cc.InstanceTypes {
489 if it.CUDA.DeviceCount == 0 {
493 _, err := strconv.ParseFloat(it.CUDA.DriverVersion, 64)
495 return fmt.Errorf("InstanceType %q has invalid CUDA.DriverVersion %q, expected format X.Y (%v)", it.Name, it.CUDA.DriverVersion, err)
497 _, err = strconv.ParseFloat(it.CUDA.HardwareCapability, 64)
499 return fmt.Errorf("InstanceType %q has invalid CUDA.HardwareCapability %q, expected format X.Y (%v)", it.Name, it.CUDA.HardwareCapability, err)
505 func checkKeyConflict(label string, m map[string]string) error {
506 saw := map[string]bool{}
508 k = strings.ToLower(k)
510 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
517 func removeNullKeys(m map[string]interface{}) {
518 for k, v := range m {
522 if v, _ := v.(map[string]interface{}); v != nil {
528 func removeSampleKeys(m map[string]interface{}) {
530 for _, v := range m {
531 if v, _ := v.(map[string]interface{}); v != nil {
537 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
538 if ldr.Logger == nil {
541 for k, vsupp := range supplied {
543 // entry will be dropped in removeSampleKeys anyway
546 vexp, ok := expected[k]
547 if expected["SAMPLE"] != nil {
548 // use the SAMPLE entry's keys as the
549 // "expected" map when checking vsupp
551 vexp = expected["SAMPLE"]
553 // check for a case-insensitive match
555 for ek := range expected {
556 if strings.EqualFold(k, ek) {
557 hint = " (perhaps you meant " + ek + "?)"
558 // If we don't delete this, it
559 // will end up getting merged,
561 // merging/overriding the
567 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s%s", prefix, k, hint)
570 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
571 // if vsupp is a map but vexp isn't map, this
572 // will be caught elsewhere; see TestBadType.
574 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
575 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
577 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
582 func (ldr *Loader) autofillPreemptible(label string, cc *arvados.Cluster) {
583 if factor := cc.Containers.PreemptiblePriceFactor; factor > 0 {
584 for name, it := range cc.InstanceTypes {
586 it.Preemptible = true
587 it.Price = it.Price * factor
588 it.Name = name + ".preemptible"
589 if it2, exists := cc.InstanceTypes[it.Name]; exists && it2 != it {
590 ldr.Logger.Warnf("%s.InstanceTypes[%s]: already exists, so not automatically adding a preemptible variant of %s", label, it.Name, name)
593 cc.InstanceTypes[it.Name] = it
600 // RegisterMetrics registers metrics showing the timestamp and content
601 // hash of the currently loaded config.
603 // Must not be called more than once for a given registry. Must not be
604 // called before Load(). Metrics are not updated by subsequent calls
606 func (ldr *Loader) RegisterMetrics(reg *prometheus.Registry) {
607 hash := fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
608 vec := prometheus.NewGaugeVec(prometheus.GaugeOpts{
609 Namespace: "arvados",
611 Name: "source_timestamp_seconds",
612 Help: "Timestamp of config file when it was loaded.",
613 }, []string{"sha256"})
614 vec.WithLabelValues(hash).Set(float64(ldr.sourceTimestamp.UnixNano()) / 1e9)
615 reg.MustRegister(vec)
617 vec = prometheus.NewGaugeVec(prometheus.GaugeOpts{
618 Namespace: "arvados",
620 Name: "load_timestamp_seconds",
621 Help: "Time when config file was loaded.",
622 }, []string{"sha256"})
623 vec.WithLabelValues(hash).Set(float64(ldr.loadTimestamp.UnixNano()) / 1e9)
624 reg.MustRegister(vec)