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
58 // NewLoader returns a new Loader with Stdin and Logger set to the
59 // given values, and all config paths set to their default values.
60 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
61 ldr := &Loader{Stdin: stdin, Logger: logger}
62 // Calling SetupFlags on a throwaway FlagSet has the side
63 // effect of assigning default values to the configurable
65 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
69 // SetupFlags configures a flagset so arguments like -config X can be
70 // used to change the loader's Path fields.
72 // ldr := NewLoader(os.Stdin, logrus.New())
73 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
74 // ldr.SetupFlags(flagset)
75 // // ldr.Path == "/etc/arvados/config.yml"
76 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
77 // // ldr.Path == "/tmp/c.yaml"
78 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
79 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
81 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
82 flagset.StringVar(&ldr.KeepWebPath, "legacy-keepweb-config", defaultKeepWebConfigPath, "Legacy keep-web configuration `file`")
83 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
84 flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
85 flagset.StringVar(&ldr.KeepproxyPath, "legacy-keepproxy-config", defaultKeepproxyConfigPath, "Legacy keepproxy configuration `file`")
86 flagset.StringVar(&ldr.GitHttpdPath, "legacy-git-httpd-config", defaultGitHttpdConfigPath, "Legacy arv-git-httpd configuration `file`")
87 flagset.StringVar(&ldr.KeepBalancePath, "legacy-keepbalance-config", defaultKeepBalanceConfigPath, "Legacy keep-balance configuration `file`")
88 flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
92 // MungeLegacyConfigArgs checks args for a -config flag whose argument
93 // is a regular file (or a symlink to one), but doesn't have a
94 // top-level "Clusters" key and therefore isn't a valid cluster
95 // configuration file. If it finds such a flag, it replaces -config
96 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
98 // This is used by programs that still need to accept "-config" as a
99 // way to specify a per-component config file until their config has
102 // If any errors are encountered while reading or parsing a config
103 // file, the given args are not munged. We presume the same errors
104 // will be encountered again and reported later on when trying to load
105 // cluster configuration from the same file, regardless of which
106 // struct we end up using.
107 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
108 munged := append([]string(nil), args...)
109 for i := 0; i < len(args); i++ {
110 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
114 if strings.Contains(args[i], "=") {
115 operand = strings.SplitN(args[i], "=", 2)[1]
116 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
122 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
125 f, err := os.Open(operand)
130 buf, err := ioutil.ReadAll(f)
134 var cfg arvados.Config
135 err = yaml.Unmarshal(buf, &cfg)
139 if len(cfg.Clusters) == 0 {
140 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
141 if operand == args[i] {
142 munged[i-1] = legacyConfigArg
144 munged[i] = legacyConfigArg + "=" + operand
149 // Disable legacy config loading for components other than the
150 // one that was specified
151 if legacyConfigArg != "-legacy-keepstore-config" {
152 ldr.KeepstorePath = ""
154 if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
155 ldr.CrunchDispatchSlurmPath = ""
157 if legacyConfigArg != "-legacy-ws-config" {
158 ldr.WebsocketPath = ""
160 if legacyConfigArg != "-legacy-keepweb-config" {
163 if legacyConfigArg != "-legacy-keepproxy-config" {
164 ldr.KeepproxyPath = ""
166 if legacyConfigArg != "-legacy-git-httpd-config" {
167 ldr.GitHttpdPath = ""
169 if legacyConfigArg != "-legacy-keepbalance-config" {
170 ldr.KeepBalancePath = ""
176 func (ldr *Loader) loadBytes(path string) ([]byte, time.Time, error) {
178 buf, err := ioutil.ReadAll(ldr.Stdin)
179 return buf, time.Now().UTC(), err
181 f, err := os.Open(path)
183 return nil, time.Time{}, err
188 return nil, time.Time{}, err
190 buf, err := ioutil.ReadAll(f)
191 return buf, fi.ModTime().UTC(), err
194 func (ldr *Loader) Load() (*arvados.Config, error) {
195 if ldr.configdata == nil {
196 buf, t, err := ldr.loadBytes(ldr.Path)
201 ldr.sourceTimestamp = t
204 // FIXME: We should reject YAML if the same key is used twice
205 // in a map/object, like {foo: bar, foo: baz}. Maybe we'll get
206 // this fixed free when we upgrade ghodss/yaml to a version
207 // that uses go-yaml v3.
209 // Load the config into a dummy map to get the cluster ID
210 // keys, discarding the values; then set up defaults for each
211 // cluster ID; then load the real config on top of the
214 Clusters map[string]struct{}
216 err := yaml.Unmarshal(ldr.configdata, &dummy)
220 if len(dummy.Clusters) == 0 {
221 return nil, ErrNoClustersDefined
224 // We can't merge deep structs here; instead, we unmarshal the
225 // default & loaded config files into generic maps, merge
226 // those, and then json-encode+decode the result into the
227 // config struct type.
228 var merged map[string]interface{}
229 for id := range dummy.Clusters {
230 var src map[string]interface{}
231 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
233 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
235 err = mergo.Merge(&merged, src, mergo.WithOverride)
237 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
240 var src map[string]interface{}
241 err = yaml.Unmarshal(ldr.configdata, &src)
243 return nil, fmt.Errorf("loading config data: %s", err)
245 ldr.logExtraKeys(merged, src, "")
246 removeSampleKeys(merged)
247 // We merge the loaded config into the default, overriding any existing keys.
248 // Make sure we do not override a default with a key that has a 'null' value.
250 err = mergo.Merge(&merged, src, mergo.WithOverride)
252 return nil, fmt.Errorf("merging config data: %s", err)
255 // map[string]interface{} => json => arvados.Config
256 var cfg arvados.Config
260 errEnc = json.NewEncoder(pw).Encode(merged)
263 err = json.NewDecoder(pr).Decode(&cfg)
268 return nil, fmt.Errorf("transcoding config data: %s", err)
271 var loadFuncs []func(*arvados.Config) error
272 if !ldr.SkipDeprecated {
273 loadFuncs = append(loadFuncs,
274 ldr.applyDeprecatedConfig,
275 ldr.applyDeprecatedVolumeDriverParameters,
279 // legacy file is required when either:
280 // * a non-default location was specified
281 // * no primary config was loaded, and this is the
282 // legacy config file for the current component
283 loadFuncs = append(loadFuncs,
284 ldr.loadOldEnvironmentVariables,
285 ldr.loadOldKeepstoreConfig,
286 ldr.loadOldKeepWebConfig,
287 ldr.loadOldCrunchDispatchSlurmConfig,
288 ldr.loadOldWebsocketConfig,
289 ldr.loadOldKeepproxyConfig,
290 ldr.loadOldGitHttpdConfig,
291 ldr.loadOldKeepBalanceConfig,
294 loadFuncs = append(loadFuncs, ldr.setImplicitStorageClasses)
295 for _, f := range loadFuncs {
302 // Preprocess/automate some configs
303 for id, cc := range cfg.Clusters {
304 ldr.autofillPreemptible("Clusters."+id, &cc)
306 if strings.Count(cc.Users.AnonymousUserToken, "/") == 3 {
307 // V2 token, strip it to just a secret
308 tmp := strings.Split(cc.Users.AnonymousUserToken, "/")
309 cc.Users.AnonymousUserToken = tmp[2]
312 cfg.Clusters[id] = cc
315 // Check for known mistakes
316 for id, cc := range cfg.Clusters {
317 for remote := range cc.RemoteClusters {
318 if remote == "*" || remote == "SAMPLE" {
321 err = ldr.checkClusterID(fmt.Sprintf("Clusters.%s.RemoteClusters.%s", id, remote), remote, true)
326 for _, err = range []error{
327 ldr.checkClusterID(fmt.Sprintf("Clusters.%s", id), id, false),
328 ldr.checkClusterID(fmt.Sprintf("Clusters.%s.Login.LoginCluster", id), cc.Login.LoginCluster, true),
329 ldr.checkToken(fmt.Sprintf("Clusters.%s.ManagementToken", id), cc.ManagementToken, true, false),
330 ldr.checkToken(fmt.Sprintf("Clusters.%s.SystemRootToken", id), cc.SystemRootToken, true, false),
331 ldr.checkToken(fmt.Sprintf("Clusters.%s.Users.AnonymousUserToken", id), cc.Users.AnonymousUserToken, false, true),
332 ldr.checkToken(fmt.Sprintf("Clusters.%s.Collections.BlobSigningKey", id), cc.Collections.BlobSigningKey, true, false),
333 checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection),
334 ldr.checkEnum("Containers.LocalKeepLogsToContainerLog", cc.Containers.LocalKeepLogsToContainerLog, "none", "all", "errors"),
335 ldr.checkEmptyKeepstores(cc),
336 ldr.checkUnlistedKeepstores(cc),
337 ldr.checkStorageClasses(cc),
338 ldr.checkCUDAVersions(cc),
339 // TODO: check non-empty Rendezvous on
340 // services other than Keepstore
347 cfg.SourceTimestamp = ldr.sourceTimestamp
348 cfg.SourceSHA256 = fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
352 var acceptableClusterIDRe = regexp.MustCompile(`^[a-z0-9]{5}$`)
354 func (ldr *Loader) checkClusterID(label, clusterID string, emptyStringOk bool) error {
355 if emptyStringOk && clusterID == "" {
357 } else if !acceptableClusterIDRe.MatchString(clusterID) {
358 return fmt.Errorf("%s: cluster ID should be 5 alphanumeric characters", label)
363 var acceptableTokenRe = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
364 var acceptableTokenLength = 32
366 func (ldr *Loader) checkToken(label, token string, mandatory bool, acceptV2 bool) error {
369 // when a token is not mandatory, the acceptable length and content is only checked if its length is non-zero
372 if ldr.Logger != nil {
373 ldr.Logger.Warnf("%s: secret token is not set (use %d+ random characters from a-z, A-Z, 0-9)", label, acceptableTokenLength)
376 } else if !acceptableTokenRe.MatchString(token) {
378 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
380 // Test for a proper V2 token
381 tmp := strings.SplitN(token, "/", 3)
383 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
385 if !strings.HasPrefix(token, "v2/") {
386 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
388 if !acceptableTokenRe.MatchString(tmp[2]) {
389 return fmt.Errorf("%s: unacceptable characters in V2 token secret (only a-z, A-Z, 0-9 are acceptable)", label)
391 if len(tmp[2]) < acceptableTokenLength {
392 ldr.Logger.Warnf("%s: secret is too short (should be at least %d characters)", label, acceptableTokenLength)
394 } else if len(token) < acceptableTokenLength {
395 if ldr.Logger != nil {
396 ldr.Logger.Warnf("%s: token is too short (should be at least %d characters)", label, acceptableTokenLength)
402 func (ldr *Loader) checkEnum(label, value string, accepted ...string) error {
403 for _, s := range accepted {
408 return fmt.Errorf("%s: unacceptable value %q: must be one of %q", label, value, accepted)
411 func (ldr *Loader) setImplicitStorageClasses(cfg *arvados.Config) error {
413 for id, cc := range cfg.Clusters {
414 if len(cc.StorageClasses) > 0 {
417 for _, vol := range cc.Volumes {
418 if len(vol.StorageClasses) > 0 {
422 // No explicit StorageClasses config info at all; fill
423 // in implicit defaults.
424 for id, vol := range cc.Volumes {
425 vol.StorageClasses = map[string]bool{"default": true}
428 cc.StorageClasses = map[string]arvados.StorageClassConfig{"default": {Default: true}}
429 cfg.Clusters[id] = cc
434 func (ldr *Loader) checkStorageClasses(cc arvados.Cluster) error {
435 classOnVolume := map[string]bool{}
436 for volid, vol := range cc.Volumes {
437 if len(vol.StorageClasses) == 0 {
438 return fmt.Errorf("%s: volume has no StorageClasses listed", volid)
440 for classid := range vol.StorageClasses {
441 if _, ok := cc.StorageClasses[classid]; !ok {
442 return fmt.Errorf("%s: volume refers to storage class %q that is not defined in StorageClasses", volid, classid)
444 classOnVolume[classid] = true
448 for classid, sc := range cc.StorageClasses {
449 if !classOnVolume[classid] && len(cc.Volumes) > 0 {
450 ldr.Logger.Warnf("there are no volumes providing storage class %q", classid)
457 return fmt.Errorf("there is no default storage class (at least one entry in StorageClasses must have Default: true)")
462 func (ldr *Loader) checkCUDAVersions(cc arvados.Cluster) error {
463 for _, it := range cc.InstanceTypes {
464 if it.CUDA.DeviceCount == 0 {
468 _, err := strconv.ParseFloat(it.CUDA.DriverVersion, 64)
470 return fmt.Errorf("InstanceType %q has invalid CUDA.DriverVersion %q, expected format X.Y (%v)", it.Name, it.CUDA.DriverVersion, err)
472 _, err = strconv.ParseFloat(it.CUDA.HardwareCapability, 64)
474 return fmt.Errorf("InstanceType %q has invalid CUDA.HardwareCapability %q, expected format X.Y (%v)", it.Name, it.CUDA.HardwareCapability, err)
480 func checkKeyConflict(label string, m map[string]string) error {
481 saw := map[string]bool{}
483 k = strings.ToLower(k)
485 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
492 func removeNullKeys(m map[string]interface{}) {
493 for k, v := range m {
497 if v, _ := v.(map[string]interface{}); v != nil {
503 func removeSampleKeys(m map[string]interface{}) {
505 for _, v := range m {
506 if v, _ := v.(map[string]interface{}); v != nil {
512 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
513 if ldr.Logger == nil {
516 for k, vsupp := range supplied {
518 // entry will be dropped in removeSampleKeys anyway
521 vexp, ok := expected[k]
522 if expected["SAMPLE"] != nil {
523 // use the SAMPLE entry's keys as the
524 // "expected" map when checking vsupp
526 vexp = expected["SAMPLE"]
528 // check for a case-insensitive match
530 for ek := range expected {
531 if strings.EqualFold(k, ek) {
532 hint = " (perhaps you meant " + ek + "?)"
533 // If we don't delete this, it
534 // will end up getting merged,
536 // merging/overriding the
542 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s%s", prefix, k, hint)
545 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
546 // if vsupp is a map but vexp isn't map, this
547 // will be caught elsewhere; see TestBadType.
549 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
550 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
552 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
557 func (ldr *Loader) autofillPreemptible(label string, cc *arvados.Cluster) {
558 if factor := cc.Containers.PreemptiblePriceFactor; factor > 0 {
559 for name, it := range cc.InstanceTypes {
561 it.Preemptible = true
562 it.Price = it.Price * factor
563 it.Name = name + ".preemptible"
564 if it2, exists := cc.InstanceTypes[it.Name]; exists && it2 != it {
565 ldr.Logger.Warnf("%s.InstanceTypes[%s]: already exists, so not automatically adding a preemptible variant of %s", label, it.Name, name)
568 cc.InstanceTypes[it.Name] = it
575 // RegisterMetrics registers metrics showing the timestamp and content
576 // hash of the currently loaded config.
578 // Must not be called more than once for a given registry. Must not be
579 // called before Load(). Metrics are not updated by subsequent calls
581 func (ldr *Loader) RegisterMetrics(reg *prometheus.Registry) {
582 vec := prometheus.NewGaugeVec(prometheus.GaugeOpts{
583 Namespace: "arvados",
585 Name: "source_timestamp_seconds",
586 Help: "Timestamp of config file when it was loaded.",
587 }, []string{"sha256"})
588 vec.WithLabelValues(fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))).Set(float64(ldr.sourceTimestamp.UnixNano()) / 1e9)
589 reg.MustRegister(vec)