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/crypto/ssh"
30 "golang.org/x/sys/unix"
33 //go:embed config.default.yml
34 var DefaultYAML []byte
36 var ErrNoClustersDefined = errors.New("config does not define any clusters")
40 Logger logrus.FieldLogger
41 SkipDeprecated bool // Don't load deprecated config keys
42 SkipLegacy bool // Don't load legacy config files
43 SkipAPICalls bool // Don't do checks that call RailsAPI/controller
48 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.KeepBalancePath, "legacy-keepbalance-config", defaultKeepBalanceConfigPath, "Legacy keep-balance configuration `file`")
91 flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
95 // MungeLegacyConfigArgs checks args for a -config flag whose argument
96 // is a regular file (or a symlink to one), but doesn't have a
97 // top-level "Clusters" key and therefore isn't a valid cluster
98 // configuration file. If it finds such a flag, it replaces -config
99 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
101 // This is used by programs that still need to accept "-config" as a
102 // way to specify a per-component config file until their config has
105 // If any errors are encountered while reading or parsing a config
106 // file, the given args are not munged. We presume the same errors
107 // will be encountered again and reported later on when trying to load
108 // cluster configuration from the same file, regardless of which
109 // struct we end up using.
110 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
111 munged := append([]string(nil), args...)
112 for i := 0; i < len(args); i++ {
113 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
117 if strings.Contains(args[i], "=") {
118 operand = strings.SplitN(args[i], "=", 2)[1]
119 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
125 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
128 f, err := os.Open(operand)
133 buf, err := ioutil.ReadAll(f)
137 var cfg arvados.Config
138 err = yaml.Unmarshal(buf, &cfg)
142 if len(cfg.Clusters) == 0 {
143 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
144 if operand == args[i] {
145 munged[i-1] = legacyConfigArg
147 munged[i] = legacyConfigArg + "=" + operand
152 // Disable legacy config loading for components other than the
153 // one that was specified
154 if legacyConfigArg != "-legacy-keepstore-config" {
155 ldr.KeepstorePath = ""
157 if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
158 ldr.CrunchDispatchSlurmPath = ""
160 if legacyConfigArg != "-legacy-ws-config" {
161 ldr.WebsocketPath = ""
163 if legacyConfigArg != "-legacy-keepweb-config" {
166 if legacyConfigArg != "-legacy-keepproxy-config" {
167 ldr.KeepproxyPath = ""
169 if legacyConfigArg != "-legacy-keepbalance-config" {
170 ldr.KeepBalancePath = ""
176 func (ldr *Loader) loadBytes(path string) (buf []byte, sourceTime, loadTime time.Time, err error) {
177 loadTime = time.Now().UTC()
179 buf, err = ioutil.ReadAll(ldr.Stdin)
180 sourceTime = loadTime
183 f, err := os.Open(path)
192 sourceTime = fi.ModTime().UTC()
193 buf, err = ioutil.ReadAll(f)
197 func (ldr *Loader) Load() (*arvados.Config, error) {
198 if ldr.configdata == nil {
199 buf, sourceTime, loadTime, err := ldr.loadBytes(ldr.Path)
204 ldr.sourceTimestamp = sourceTime
205 ldr.loadTimestamp = loadTime
208 // FIXME: We should reject YAML if the same key is used twice
209 // in a map/object, like {foo: bar, foo: baz}. Maybe we'll get
210 // this fixed free when we upgrade ghodss/yaml to a version
211 // that uses go-yaml v3.
213 // Load the config into a dummy map to get the cluster ID
214 // keys, discarding the values; then set up defaults for each
215 // cluster ID; then load the real config on top of the
218 Clusters map[string]struct{}
220 err := yaml.Unmarshal(ldr.configdata, &dummy)
224 if len(dummy.Clusters) == 0 {
225 return nil, ErrNoClustersDefined
228 // We can't merge deep structs here; instead, we unmarshal the
229 // default & loaded config files into generic maps, merge
230 // those, and then json-encode+decode the result into the
231 // config struct type.
232 var merged map[string]interface{}
233 for id := range dummy.Clusters {
234 var src map[string]interface{}
235 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
237 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
239 err = mergo.Merge(&merged, src, mergo.WithOverride)
241 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
244 var src map[string]interface{}
245 err = yaml.Unmarshal(ldr.configdata, &src)
247 return nil, fmt.Errorf("loading config data: %s", err)
249 ldr.logExtraKeys(merged, src, "")
250 removeSampleKeys(merged)
251 // We merge the loaded config into the default, overriding any existing keys.
252 // Make sure we do not override a default with a key that has a 'null' value.
254 err = mergo.Merge(&merged, src, mergo.WithOverride)
256 return nil, fmt.Errorf("merging config data: %s", err)
259 // map[string]interface{} => json => arvados.Config
260 var cfg arvados.Config
264 errEnc = json.NewEncoder(pw).Encode(merged)
267 err = json.NewDecoder(pr).Decode(&cfg)
272 return nil, fmt.Errorf("transcoding config data: %s", err)
275 var loadFuncs []func(*arvados.Config) error
276 if !ldr.SkipDeprecated {
277 loadFuncs = append(loadFuncs,
278 ldr.applyDeprecatedConfig,
279 ldr.applyDeprecatedVolumeDriverParameters,
283 // legacy file is required when either:
284 // * a non-default location was specified
285 // * no primary config was loaded, and this is the
286 // legacy config file for the current component
287 loadFuncs = append(loadFuncs,
288 ldr.loadOldEnvironmentVariables,
289 ldr.loadOldKeepstoreConfig,
290 ldr.loadOldKeepWebConfig,
291 ldr.loadOldCrunchDispatchSlurmConfig,
292 ldr.loadOldWebsocketConfig,
293 ldr.loadOldKeepproxyConfig,
294 ldr.loadOldKeepBalanceConfig,
297 loadFuncs = append(loadFuncs,
298 ldr.setImplicitStorageClasses,
299 ldr.setLoopbackInstanceType,
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 lowercase 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) setLoopbackInstanceType(cfg *arvados.Config) error {
419 for id, cc := range cfg.Clusters {
420 if !cc.Containers.CloudVMs.Enable || cc.Containers.CloudVMs.Driver != "loopback" {
423 if len(cc.InstanceTypes) == 1 {
426 if len(cc.InstanceTypes) > 1 {
427 return fmt.Errorf("Clusters.%s.InstanceTypes: cannot use multiple InstanceTypes with loopback driver", id)
429 // No InstanceTypes configured. Fill in implicit
431 hostram, err := getHostRAM()
435 scratch, err := getFilesystemSize(os.TempDir())
439 cc.InstanceTypes = arvados.InstanceTypeMap{"localhost": {
441 ProviderType: "localhost",
442 VCPUs: runtime.NumCPU(),
445 IncludedScratch: scratch,
448 cfg.Clusters[id] = cc
453 func getFilesystemSize(path string) (arvados.ByteSize, error) {
454 var stat unix.Statfs_t
455 err := unix.Statfs(path, &stat)
459 return arvados.ByteSize(stat.Blocks * uint64(stat.Bsize)), nil
462 var reMemTotal = regexp.MustCompile(`(^|\n)MemTotal: *(\d+) kB\n`)
464 func getHostRAM() (arvados.ByteSize, error) {
465 buf, err := os.ReadFile("/proc/meminfo")
469 m := reMemTotal.FindSubmatch(buf)
471 return 0, errors.New("error parsing /proc/meminfo: no MemTotal")
473 kb, err := strconv.ParseInt(string(m[2]), 10, 64)
475 return 0, fmt.Errorf("error parsing /proc/meminfo: %q: %w", m[2], err)
477 return arvados.ByteSize(kb) * 1024, nil
480 func (ldr *Loader) setImplicitStorageClasses(cfg *arvados.Config) error {
482 for id, cc := range cfg.Clusters {
483 if len(cc.StorageClasses) > 0 {
486 for _, vol := range cc.Volumes {
487 if len(vol.StorageClasses) > 0 {
491 // No explicit StorageClasses config info at all; fill
492 // in implicit defaults.
493 for id, vol := range cc.Volumes {
494 vol.StorageClasses = map[string]bool{"default": true}
497 cc.StorageClasses = map[string]arvados.StorageClassConfig{"default": {Default: true}}
498 cfg.Clusters[id] = cc
503 func (ldr *Loader) checkLocalKeepBlobBuffers(cc arvados.Cluster) error {
504 kbb := cc.Containers.LocalKeepBlobBuffersPerVCPU
508 for uuid, vol := range cc.Volumes {
509 if len(vol.AccessViaHosts) > 0 {
510 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)
513 if !vol.ReadOnly && vol.Replication < cc.Collections.DefaultReplication {
514 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)
521 func (ldr *Loader) checkStorageClasses(cc arvados.Cluster) error {
522 classOnVolume := map[string]bool{}
523 for volid, vol := range cc.Volumes {
524 if len(vol.StorageClasses) == 0 {
525 return fmt.Errorf("%s: volume has no StorageClasses listed", volid)
527 for classid := range vol.StorageClasses {
528 if _, ok := cc.StorageClasses[classid]; !ok {
529 return fmt.Errorf("%s: volume refers to storage class %q that is not defined in StorageClasses", volid, classid)
531 classOnVolume[classid] = true
535 for classid, sc := range cc.StorageClasses {
536 if !classOnVolume[classid] && len(cc.Volumes) > 0 {
537 ldr.Logger.Warnf("there are no volumes providing storage class %q", classid)
544 return fmt.Errorf("there is no default storage class (at least one entry in StorageClasses must have Default: true)")
549 func (ldr *Loader) checkCUDAVersions(cc arvados.Cluster) error {
550 for _, it := range cc.InstanceTypes {
551 if it.CUDA.DeviceCount == 0 {
555 _, err := strconv.ParseFloat(it.CUDA.DriverVersion, 64)
557 return fmt.Errorf("InstanceType %q has invalid CUDA.DriverVersion %q, expected format X.Y (%v)", it.Name, it.CUDA.DriverVersion, err)
559 _, err = strconv.ParseFloat(it.CUDA.HardwareCapability, 64)
561 return fmt.Errorf("InstanceType %q has invalid CUDA.HardwareCapability %q, expected format X.Y (%v)", it.Name, it.CUDA.HardwareCapability, err)
567 func checkKeyConflict(label string, m map[string]string) error {
568 saw := map[string]bool{}
570 k = strings.ToLower(k)
572 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
579 func removeNullKeys(m map[string]interface{}) {
580 for k, v := range m {
584 if v, _ := v.(map[string]interface{}); v != nil {
590 func removeSampleKeys(m map[string]interface{}) {
592 for _, v := range m {
593 if v, _ := v.(map[string]interface{}); v != nil {
599 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
600 if ldr.Logger == nil {
603 for k, vsupp := range supplied {
605 // entry will be dropped in removeSampleKeys anyway
608 vexp, ok := expected[k]
609 if expected["SAMPLE"] != nil {
610 // use the SAMPLE entry's keys as the
611 // "expected" map when checking vsupp
613 vexp = expected["SAMPLE"]
615 // check for a case-insensitive match
617 for ek := range expected {
618 if strings.EqualFold(k, ek) {
619 hint = " (perhaps you meant " + ek + "?)"
620 // If we don't delete this, it
621 // will end up getting merged,
623 // merging/overriding the
629 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s%s", prefix, k, hint)
632 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
633 // if vsupp is a map but vexp isn't map, this
634 // will be caught elsewhere; see TestBadType.
636 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
637 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
639 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
644 func (ldr *Loader) autofillPreemptible(label string, cc *arvados.Cluster) {
645 if factor := cc.Containers.PreemptiblePriceFactor; factor > 0 {
646 for name, it := range cc.InstanceTypes {
648 it.Preemptible = true
649 it.Price = it.Price * factor
650 it.Name = name + ".preemptible"
651 if it2, exists := cc.InstanceTypes[it.Name]; exists && it2 != it {
652 ldr.Logger.Warnf("%s.InstanceTypes[%s]: already exists, so not automatically adding a preemptible variant of %s", label, it.Name, name)
655 cc.InstanceTypes[it.Name] = it
662 // RegisterMetrics registers metrics showing the timestamp and content
663 // hash of the currently loaded config.
665 // Must not be called more than once for a given registry. Must not be
666 // called before Load(). Metrics are not updated by subsequent calls
668 func (ldr *Loader) RegisterMetrics(reg *prometheus.Registry) {
669 hash := fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
670 vec := prometheus.NewGaugeVec(prometheus.GaugeOpts{
671 Namespace: "arvados",
673 Name: "source_timestamp_seconds",
674 Help: "Timestamp of config file when it was loaded.",
675 }, []string{"sha256"})
676 vec.WithLabelValues(hash).Set(float64(ldr.sourceTimestamp.UnixNano()) / 1e9)
677 reg.MustRegister(vec)
679 vec = prometheus.NewGaugeVec(prometheus.GaugeOpts{
680 Namespace: "arvados",
682 Name: "load_timestamp_seconds",
683 Help: "Time when config file was loaded.",
684 }, []string{"sha256"})
685 vec.WithLabelValues(hash).Set(float64(ldr.loadTimestamp.UnixNano()) / 1e9)
686 reg.MustRegister(vec)
689 // Load an SSH private key from the given confvalue, which is either
690 // the literal key or an absolute path to a file containing the key.
691 func LoadSSHKey(confvalue string) (ssh.Signer, error) {
692 if fnm := strings.TrimPrefix(confvalue, "file://"); fnm != confvalue && strings.HasPrefix(fnm, "/") {
693 keydata, err := os.ReadFile(fnm)
697 return ssh.ParsePrivateKey(keydata)
699 return ssh.ParsePrivateKey([]byte(confvalue))