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.checkStorageClasses(cc),
344 ldr.checkCUDAVersions(cc),
345 // TODO: check non-empty Rendezvous on
346 // services other than Keepstore
353 cfg.SourceTimestamp = ldr.sourceTimestamp
354 cfg.SourceSHA256 = fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
358 var acceptableClusterIDRe = regexp.MustCompile(`^[a-z0-9]{5}$`)
360 func (ldr *Loader) checkClusterID(label, clusterID string, emptyStringOk bool) error {
361 if emptyStringOk && clusterID == "" {
363 } else if !acceptableClusterIDRe.MatchString(clusterID) {
364 return fmt.Errorf("%s: cluster ID should be 5 alphanumeric characters", label)
369 var acceptableTokenRe = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
370 var acceptableTokenLength = 32
372 func (ldr *Loader) checkToken(label, token string, mandatory bool, acceptV2 bool) error {
375 // when a token is not mandatory, the acceptable length and content is only checked if its length is non-zero
378 if ldr.Logger != nil {
379 ldr.Logger.Warnf("%s: secret token is not set (use %d+ random characters from a-z, A-Z, 0-9)", label, acceptableTokenLength)
382 } else if !acceptableTokenRe.MatchString(token) {
384 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
386 // Test for a proper V2 token
387 tmp := strings.SplitN(token, "/", 3)
389 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
391 if !strings.HasPrefix(token, "v2/") {
392 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
394 if !acceptableTokenRe.MatchString(tmp[2]) {
395 return fmt.Errorf("%s: unacceptable characters in V2 token secret (only a-z, A-Z, 0-9 are acceptable)", label)
397 if len(tmp[2]) < acceptableTokenLength {
398 ldr.Logger.Warnf("%s: secret is too short (should be at least %d characters)", label, acceptableTokenLength)
400 } else if len(token) < acceptableTokenLength {
401 if ldr.Logger != nil {
402 ldr.Logger.Warnf("%s: token is too short (should be at least %d characters)", label, acceptableTokenLength)
408 func (ldr *Loader) checkEnum(label, value string, accepted ...string) error {
409 for _, s := range accepted {
414 return fmt.Errorf("%s: unacceptable value %q: must be one of %q", label, value, accepted)
417 func (ldr *Loader) setImplicitStorageClasses(cfg *arvados.Config) error {
419 for id, cc := range cfg.Clusters {
420 if len(cc.StorageClasses) > 0 {
423 for _, vol := range cc.Volumes {
424 if len(vol.StorageClasses) > 0 {
428 // No explicit StorageClasses config info at all; fill
429 // in implicit defaults.
430 for id, vol := range cc.Volumes {
431 vol.StorageClasses = map[string]bool{"default": true}
434 cc.StorageClasses = map[string]arvados.StorageClassConfig{"default": {Default: true}}
435 cfg.Clusters[id] = cc
440 func (ldr *Loader) checkStorageClasses(cc arvados.Cluster) error {
441 classOnVolume := map[string]bool{}
442 for volid, vol := range cc.Volumes {
443 if len(vol.StorageClasses) == 0 {
444 return fmt.Errorf("%s: volume has no StorageClasses listed", volid)
446 for classid := range vol.StorageClasses {
447 if _, ok := cc.StorageClasses[classid]; !ok {
448 return fmt.Errorf("%s: volume refers to storage class %q that is not defined in StorageClasses", volid, classid)
450 classOnVolume[classid] = true
454 for classid, sc := range cc.StorageClasses {
455 if !classOnVolume[classid] && len(cc.Volumes) > 0 {
456 ldr.Logger.Warnf("there are no volumes providing storage class %q", classid)
463 return fmt.Errorf("there is no default storage class (at least one entry in StorageClasses must have Default: true)")
468 func (ldr *Loader) checkCUDAVersions(cc arvados.Cluster) error {
469 for _, it := range cc.InstanceTypes {
470 if it.CUDA.DeviceCount == 0 {
474 _, err := strconv.ParseFloat(it.CUDA.DriverVersion, 64)
476 return fmt.Errorf("InstanceType %q has invalid CUDA.DriverVersion %q, expected format X.Y (%v)", it.Name, it.CUDA.DriverVersion, err)
478 _, err = strconv.ParseFloat(it.CUDA.HardwareCapability, 64)
480 return fmt.Errorf("InstanceType %q has invalid CUDA.HardwareCapability %q, expected format X.Y (%v)", it.Name, it.CUDA.HardwareCapability, err)
486 func checkKeyConflict(label string, m map[string]string) error {
487 saw := map[string]bool{}
489 k = strings.ToLower(k)
491 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
498 func removeNullKeys(m map[string]interface{}) {
499 for k, v := range m {
503 if v, _ := v.(map[string]interface{}); v != nil {
509 func removeSampleKeys(m map[string]interface{}) {
511 for _, v := range m {
512 if v, _ := v.(map[string]interface{}); v != nil {
518 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
519 if ldr.Logger == nil {
522 for k, vsupp := range supplied {
524 // entry will be dropped in removeSampleKeys anyway
527 vexp, ok := expected[k]
528 if expected["SAMPLE"] != nil {
529 // use the SAMPLE entry's keys as the
530 // "expected" map when checking vsupp
532 vexp = expected["SAMPLE"]
534 // check for a case-insensitive match
536 for ek := range expected {
537 if strings.EqualFold(k, ek) {
538 hint = " (perhaps you meant " + ek + "?)"
539 // If we don't delete this, it
540 // will end up getting merged,
542 // merging/overriding the
548 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s%s", prefix, k, hint)
551 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
552 // if vsupp is a map but vexp isn't map, this
553 // will be caught elsewhere; see TestBadType.
555 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
556 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
558 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
563 func (ldr *Loader) autofillPreemptible(label string, cc *arvados.Cluster) {
564 if factor := cc.Containers.PreemptiblePriceFactor; factor > 0 {
565 for name, it := range cc.InstanceTypes {
567 it.Preemptible = true
568 it.Price = it.Price * factor
569 it.Name = name + ".preemptible"
570 if it2, exists := cc.InstanceTypes[it.Name]; exists && it2 != it {
571 ldr.Logger.Warnf("%s.InstanceTypes[%s]: already exists, so not automatically adding a preemptible variant of %s", label, it.Name, name)
574 cc.InstanceTypes[it.Name] = it
581 // RegisterMetrics registers metrics showing the timestamp and content
582 // hash of the currently loaded config.
584 // Must not be called more than once for a given registry. Must not be
585 // called before Load(). Metrics are not updated by subsequent calls
587 func (ldr *Loader) RegisterMetrics(reg *prometheus.Registry) {
588 hash := fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
589 vec := prometheus.NewGaugeVec(prometheus.GaugeOpts{
590 Namespace: "arvados",
592 Name: "source_timestamp_seconds",
593 Help: "Timestamp of config file when it was loaded.",
594 }, []string{"sha256"})
595 vec.WithLabelValues(hash).Set(float64(ldr.sourceTimestamp.UnixNano()) / 1e9)
596 reg.MustRegister(vec)
598 vec = prometheus.NewGaugeVec(prometheus.GaugeOpts{
599 Namespace: "arvados",
601 Name: "load_timestamp_seconds",
602 Help: "Time when config file was loaded.",
603 }, []string{"sha256"})
604 vec.WithLabelValues(hash).Set(float64(ldr.loadTimestamp.UnixNano()) / 1e9)
605 reg.MustRegister(vec)