1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 "github.com/ghodss/yaml"
26 "github.com/imdario/mergo"
27 "github.com/prometheus/client_golang/prometheus"
28 "github.com/sirupsen/logrus"
29 "golang.org/x/sys/unix"
32 //go:embed config.default.yml
33 var DefaultYAML []byte
35 var ErrNoClustersDefined = errors.New("config does not define any clusters")
39 Logger logrus.FieldLogger
40 SkipDeprecated bool // Don't load deprecated config keys
41 SkipLegacy bool // Don't load legacy config files
42 SkipAPICalls bool // Don't do checks that call RailsAPI/controller
47 CrunchDispatchSlurmPath string
51 KeepBalancePath string
54 // UTC time for configdata: either the modtime of the file we
55 // read configdata from, or the time when we read configdata
57 sourceTimestamp time.Time
58 // UTC time when configdata was read.
59 loadTimestamp time.Time
62 // NewLoader returns a new Loader with Stdin and Logger set to the
63 // given values, and all config paths set to their default values.
64 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
65 ldr := &Loader{Stdin: stdin, Logger: logger}
66 // Calling SetupFlags on a throwaway FlagSet has the side
67 // effect of assigning default values to the configurable
69 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
73 // SetupFlags configures a flagset so arguments like -config X can be
74 // used to change the loader's Path fields.
76 // ldr := NewLoader(os.Stdin, logrus.New())
77 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
78 // ldr.SetupFlags(flagset)
79 // // ldr.Path == "/etc/arvados/config.yml"
80 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
81 // // ldr.Path == "/tmp/c.yaml"
82 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
83 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
85 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
86 flagset.StringVar(&ldr.KeepWebPath, "legacy-keepweb-config", defaultKeepWebConfigPath, "Legacy keep-web configuration `file`")
87 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
88 flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
89 flagset.StringVar(&ldr.KeepproxyPath, "legacy-keepproxy-config", defaultKeepproxyConfigPath, "Legacy keepproxy configuration `file`")
90 flagset.StringVar(&ldr.GitHttpdPath, "legacy-git-httpd-config", defaultGitHttpdConfigPath, "Legacy arvados-git-httpd configuration `file`")
91 flagset.StringVar(&ldr.KeepBalancePath, "legacy-keepbalance-config", defaultKeepBalanceConfigPath, "Legacy keep-balance configuration `file`")
92 flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
96 // MungeLegacyConfigArgs checks args for a -config flag whose argument
97 // is a regular file (or a symlink to one), but doesn't have a
98 // top-level "Clusters" key and therefore isn't a valid cluster
99 // configuration file. If it finds such a flag, it replaces -config
100 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
102 // This is used by programs that still need to accept "-config" as a
103 // way to specify a per-component config file until their config has
106 // If any errors are encountered while reading or parsing a config
107 // file, the given args are not munged. We presume the same errors
108 // will be encountered again and reported later on when trying to load
109 // cluster configuration from the same file, regardless of which
110 // struct we end up using.
111 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
112 munged := append([]string(nil), args...)
113 for i := 0; i < len(args); i++ {
114 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
118 if strings.Contains(args[i], "=") {
119 operand = strings.SplitN(args[i], "=", 2)[1]
120 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
126 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
129 f, err := os.Open(operand)
134 buf, err := ioutil.ReadAll(f)
138 var cfg arvados.Config
139 err = yaml.Unmarshal(buf, &cfg)
143 if len(cfg.Clusters) == 0 {
144 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
145 if operand == args[i] {
146 munged[i-1] = legacyConfigArg
148 munged[i] = legacyConfigArg + "=" + operand
153 // Disable legacy config loading for components other than the
154 // one that was specified
155 if legacyConfigArg != "-legacy-keepstore-config" {
156 ldr.KeepstorePath = ""
158 if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
159 ldr.CrunchDispatchSlurmPath = ""
161 if legacyConfigArg != "-legacy-ws-config" {
162 ldr.WebsocketPath = ""
164 if legacyConfigArg != "-legacy-keepweb-config" {
167 if legacyConfigArg != "-legacy-keepproxy-config" {
168 ldr.KeepproxyPath = ""
170 if legacyConfigArg != "-legacy-git-httpd-config" {
171 ldr.GitHttpdPath = ""
173 if legacyConfigArg != "-legacy-keepbalance-config" {
174 ldr.KeepBalancePath = ""
180 func (ldr *Loader) loadBytes(path string) (buf []byte, sourceTime, loadTime time.Time, err error) {
181 loadTime = time.Now().UTC()
183 buf, err = ioutil.ReadAll(ldr.Stdin)
184 sourceTime = loadTime
187 f, err := os.Open(path)
196 sourceTime = fi.ModTime().UTC()
197 buf, err = ioutil.ReadAll(f)
201 func (ldr *Loader) Load() (*arvados.Config, error) {
202 if ldr.configdata == nil {
203 buf, sourceTime, loadTime, err := ldr.loadBytes(ldr.Path)
208 ldr.sourceTimestamp = sourceTime
209 ldr.loadTimestamp = loadTime
212 // FIXME: We should reject YAML if the same key is used twice
213 // in a map/object, like {foo: bar, foo: baz}. Maybe we'll get
214 // this fixed free when we upgrade ghodss/yaml to a version
215 // that uses go-yaml v3.
217 // Load the config into a dummy map to get the cluster ID
218 // keys, discarding the values; then set up defaults for each
219 // cluster ID; then load the real config on top of the
222 Clusters map[string]struct{}
224 err := yaml.Unmarshal(ldr.configdata, &dummy)
228 if len(dummy.Clusters) == 0 {
229 return nil, ErrNoClustersDefined
232 // We can't merge deep structs here; instead, we unmarshal the
233 // default & loaded config files into generic maps, merge
234 // those, and then json-encode+decode the result into the
235 // config struct type.
236 var merged map[string]interface{}
237 for id := range dummy.Clusters {
238 var src map[string]interface{}
239 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
241 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
243 err = mergo.Merge(&merged, src, mergo.WithOverride)
245 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
248 var src map[string]interface{}
249 err = yaml.Unmarshal(ldr.configdata, &src)
251 return nil, fmt.Errorf("loading config data: %s", err)
253 ldr.logExtraKeys(merged, src, "")
254 removeSampleKeys(merged)
255 // We merge the loaded config into the default, overriding any existing keys.
256 // Make sure we do not override a default with a key that has a 'null' value.
258 err = mergo.Merge(&merged, src, mergo.WithOverride)
260 return nil, fmt.Errorf("merging config data: %s", err)
263 // map[string]interface{} => json => arvados.Config
264 var cfg arvados.Config
268 errEnc = json.NewEncoder(pw).Encode(merged)
271 err = json.NewDecoder(pr).Decode(&cfg)
276 return nil, fmt.Errorf("transcoding config data: %s", err)
279 var loadFuncs []func(*arvados.Config) error
280 if !ldr.SkipDeprecated {
281 loadFuncs = append(loadFuncs,
282 ldr.applyDeprecatedConfig,
283 ldr.applyDeprecatedVolumeDriverParameters,
287 // legacy file is required when either:
288 // * a non-default location was specified
289 // * no primary config was loaded, and this is the
290 // legacy config file for the current component
291 loadFuncs = append(loadFuncs,
292 ldr.loadOldEnvironmentVariables,
293 ldr.loadOldKeepstoreConfig,
294 ldr.loadOldKeepWebConfig,
295 ldr.loadOldCrunchDispatchSlurmConfig,
296 ldr.loadOldWebsocketConfig,
297 ldr.loadOldKeepproxyConfig,
298 ldr.loadOldGitHttpdConfig,
299 ldr.loadOldKeepBalanceConfig,
302 loadFuncs = append(loadFuncs,
303 ldr.setImplicitStorageClasses,
304 ldr.setLoopbackInstanceType,
306 for _, f := range loadFuncs {
313 // Preprocess/automate some configs
314 for id, cc := range cfg.Clusters {
315 ldr.autofillPreemptible("Clusters."+id, &cc)
317 if strings.Count(cc.Users.AnonymousUserToken, "/") == 3 {
318 // V2 token, strip it to just a secret
319 tmp := strings.Split(cc.Users.AnonymousUserToken, "/")
320 cc.Users.AnonymousUserToken = tmp[2]
323 cfg.Clusters[id] = cc
326 // Check for known mistakes
327 for id, cc := range cfg.Clusters {
328 for remote := range cc.RemoteClusters {
329 if remote == "*" || remote == "SAMPLE" {
332 err = ldr.checkClusterID(fmt.Sprintf("Clusters.%s.RemoteClusters.%s", id, remote), remote, true)
337 for _, err = range []error{
338 ldr.checkClusterID(fmt.Sprintf("Clusters.%s", id), id, false),
339 ldr.checkClusterID(fmt.Sprintf("Clusters.%s.Login.LoginCluster", id), cc.Login.LoginCluster, true),
340 ldr.checkToken(fmt.Sprintf("Clusters.%s.ManagementToken", id), cc.ManagementToken, true, false),
341 ldr.checkToken(fmt.Sprintf("Clusters.%s.SystemRootToken", id), cc.SystemRootToken, true, false),
342 ldr.checkToken(fmt.Sprintf("Clusters.%s.Users.AnonymousUserToken", id), cc.Users.AnonymousUserToken, false, true),
343 ldr.checkToken(fmt.Sprintf("Clusters.%s.Collections.BlobSigningKey", id), cc.Collections.BlobSigningKey, true, false),
344 checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection),
345 ldr.checkEnum("Containers.LocalKeepLogsToContainerLog", cc.Containers.LocalKeepLogsToContainerLog, "none", "all", "errors"),
346 ldr.checkEmptyKeepstores(cc),
347 ldr.checkUnlistedKeepstores(cc),
348 ldr.checkLocalKeepBlobBuffers(cc),
349 ldr.checkStorageClasses(cc),
350 ldr.checkCUDAVersions(cc),
351 // TODO: check non-empty Rendezvous on
352 // services other than Keepstore
359 cfg.SourceTimestamp = ldr.sourceTimestamp
360 cfg.SourceSHA256 = fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
364 var acceptableClusterIDRe = regexp.MustCompile(`^[a-z0-9]{5}$`)
366 func (ldr *Loader) checkClusterID(label, clusterID string, emptyStringOk bool) error {
367 if emptyStringOk && clusterID == "" {
369 } else if !acceptableClusterIDRe.MatchString(clusterID) {
370 return fmt.Errorf("%s: cluster ID should be 5 lowercase alphanumeric characters", label)
375 var acceptableTokenRe = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
376 var acceptableTokenLength = 32
378 func (ldr *Loader) checkToken(label, token string, mandatory bool, acceptV2 bool) error {
381 // when a token is not mandatory, the acceptable length and content is only checked if its length is non-zero
384 if ldr.Logger != nil {
385 ldr.Logger.Warnf("%s: secret token is not set (use %d+ random characters from a-z, A-Z, 0-9)", label, acceptableTokenLength)
388 } else if !acceptableTokenRe.MatchString(token) {
390 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
392 // Test for a proper V2 token
393 tmp := strings.SplitN(token, "/", 3)
395 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
397 if !strings.HasPrefix(token, "v2/") {
398 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
400 if !acceptableTokenRe.MatchString(tmp[2]) {
401 return fmt.Errorf("%s: unacceptable characters in V2 token secret (only a-z, A-Z, 0-9 are acceptable)", label)
403 if len(tmp[2]) < acceptableTokenLength {
404 ldr.Logger.Warnf("%s: secret is too short (should be at least %d characters)", label, acceptableTokenLength)
406 } else if len(token) < acceptableTokenLength {
407 if ldr.Logger != nil {
408 ldr.Logger.Warnf("%s: token is too short (should be at least %d characters)", label, acceptableTokenLength)
414 func (ldr *Loader) checkEnum(label, value string, accepted ...string) error {
415 for _, s := range accepted {
420 return fmt.Errorf("%s: unacceptable value %q: must be one of %q", label, value, accepted)
423 func (ldr *Loader) setLoopbackInstanceType(cfg *arvados.Config) error {
424 for id, cc := range cfg.Clusters {
425 if !cc.Containers.CloudVMs.Enable || cc.Containers.CloudVMs.Driver != "loopback" {
428 if len(cc.InstanceTypes) == 1 {
431 if len(cc.InstanceTypes) > 1 {
432 return fmt.Errorf("Clusters.%s.InstanceTypes: cannot use multiple InstanceTypes with loopback driver", id)
434 // No InstanceTypes configured. Fill in implicit
436 hostram, err := getHostRAM()
440 scratch, err := getFilesystemSize(os.TempDir())
444 cc.InstanceTypes = arvados.InstanceTypeMap{"localhost": {
446 ProviderType: "localhost",
447 VCPUs: runtime.NumCPU(),
450 IncludedScratch: scratch,
453 cfg.Clusters[id] = cc
458 func getFilesystemSize(path string) (arvados.ByteSize, error) {
459 var stat unix.Statfs_t
460 err := unix.Statfs(path, &stat)
464 return arvados.ByteSize(stat.Blocks * uint64(stat.Bsize)), nil
467 var reMemTotal = regexp.MustCompile(`(^|\n)MemTotal: *(\d+) kB\n`)
469 func getHostRAM() (arvados.ByteSize, error) {
470 buf, err := os.ReadFile("/proc/meminfo")
474 m := reMemTotal.FindSubmatch(buf)
476 return 0, errors.New("error parsing /proc/meminfo: no MemTotal")
478 kb, err := strconv.ParseInt(string(m[2]), 10, 64)
480 return 0, fmt.Errorf("error parsing /proc/meminfo: %q: %w", m[2], err)
482 return arvados.ByteSize(kb) * 1024, nil
485 func (ldr *Loader) setImplicitStorageClasses(cfg *arvados.Config) error {
487 for id, cc := range cfg.Clusters {
488 if len(cc.StorageClasses) > 0 {
491 for _, vol := range cc.Volumes {
492 if len(vol.StorageClasses) > 0 {
496 // No explicit StorageClasses config info at all; fill
497 // in implicit defaults.
498 for id, vol := range cc.Volumes {
499 vol.StorageClasses = map[string]bool{"default": true}
502 cc.StorageClasses = map[string]arvados.StorageClassConfig{"default": {Default: true}}
503 cfg.Clusters[id] = cc
508 func (ldr *Loader) checkLocalKeepBlobBuffers(cc arvados.Cluster) error {
509 kbb := cc.Containers.LocalKeepBlobBuffersPerVCPU
513 for uuid, vol := range cc.Volumes {
514 if len(vol.AccessViaHosts) > 0 {
515 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)
518 if !vol.ReadOnly && vol.Replication < cc.Collections.DefaultReplication {
519 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)
526 func (ldr *Loader) checkStorageClasses(cc arvados.Cluster) error {
527 classOnVolume := map[string]bool{}
528 for volid, vol := range cc.Volumes {
529 if len(vol.StorageClasses) == 0 {
530 return fmt.Errorf("%s: volume has no StorageClasses listed", volid)
532 for classid := range vol.StorageClasses {
533 if _, ok := cc.StorageClasses[classid]; !ok {
534 return fmt.Errorf("%s: volume refers to storage class %q that is not defined in StorageClasses", volid, classid)
536 classOnVolume[classid] = true
540 for classid, sc := range cc.StorageClasses {
541 if !classOnVolume[classid] && len(cc.Volumes) > 0 {
542 ldr.Logger.Warnf("there are no volumes providing storage class %q", classid)
549 return fmt.Errorf("there is no default storage class (at least one entry in StorageClasses must have Default: true)")
554 func (ldr *Loader) checkCUDAVersions(cc arvados.Cluster) error {
555 for _, it := range cc.InstanceTypes {
556 if it.CUDA.DeviceCount == 0 {
560 _, err := strconv.ParseFloat(it.CUDA.DriverVersion, 64)
562 return fmt.Errorf("InstanceType %q has invalid CUDA.DriverVersion %q, expected format X.Y (%v)", it.Name, it.CUDA.DriverVersion, err)
564 _, err = strconv.ParseFloat(it.CUDA.HardwareCapability, 64)
566 return fmt.Errorf("InstanceType %q has invalid CUDA.HardwareCapability %q, expected format X.Y (%v)", it.Name, it.CUDA.HardwareCapability, err)
572 func checkKeyConflict(label string, m map[string]string) error {
573 saw := map[string]bool{}
575 k = strings.ToLower(k)
577 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
584 func removeNullKeys(m map[string]interface{}) {
585 for k, v := range m {
589 if v, _ := v.(map[string]interface{}); v != nil {
595 func removeSampleKeys(m map[string]interface{}) {
597 for _, v := range m {
598 if v, _ := v.(map[string]interface{}); v != nil {
604 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
605 if ldr.Logger == nil {
608 for k, vsupp := range supplied {
610 // entry will be dropped in removeSampleKeys anyway
613 vexp, ok := expected[k]
614 if expected["SAMPLE"] != nil {
615 // use the SAMPLE entry's keys as the
616 // "expected" map when checking vsupp
618 vexp = expected["SAMPLE"]
620 // check for a case-insensitive match
622 for ek := range expected {
623 if strings.EqualFold(k, ek) {
624 hint = " (perhaps you meant " + ek + "?)"
625 // If we don't delete this, it
626 // will end up getting merged,
628 // merging/overriding the
634 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s%s", prefix, k, hint)
637 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
638 // if vsupp is a map but vexp isn't map, this
639 // will be caught elsewhere; see TestBadType.
641 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
642 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
644 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
649 func (ldr *Loader) autofillPreemptible(label string, cc *arvados.Cluster) {
650 if factor := cc.Containers.PreemptiblePriceFactor; factor > 0 {
651 for name, it := range cc.InstanceTypes {
653 it.Preemptible = true
654 it.Price = it.Price * factor
655 it.Name = name + ".preemptible"
656 if it2, exists := cc.InstanceTypes[it.Name]; exists && it2 != it {
657 ldr.Logger.Warnf("%s.InstanceTypes[%s]: already exists, so not automatically adding a preemptible variant of %s", label, it.Name, name)
660 cc.InstanceTypes[it.Name] = it
667 // RegisterMetrics registers metrics showing the timestamp and content
668 // hash of the currently loaded config.
670 // Must not be called more than once for a given registry. Must not be
671 // called before Load(). Metrics are not updated by subsequent calls
673 func (ldr *Loader) RegisterMetrics(reg *prometheus.Registry) {
674 hash := fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
675 vec := prometheus.NewGaugeVec(prometheus.GaugeOpts{
676 Namespace: "arvados",
678 Name: "source_timestamp_seconds",
679 Help: "Timestamp of config file when it was loaded.",
680 }, []string{"sha256"})
681 vec.WithLabelValues(hash).Set(float64(ldr.sourceTimestamp.UnixNano()) / 1e9)
682 reg.MustRegister(vec)
684 vec = prometheus.NewGaugeVec(prometheus.GaugeOpts{
685 Namespace: "arvados",
687 Name: "load_timestamp_seconds",
688 Help: "Time when config file was loaded.",
689 }, []string{"sha256"})
690 vec.WithLabelValues(hash).Set(float64(ldr.loadTimestamp.UnixNano()) / 1e9)
691 reg.MustRegister(vec)