1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.arvados.org/arvados.git/sdk/go/arvados"
23 "github.com/ghodss/yaml"
24 "github.com/imdario/mergo"
25 "github.com/sirupsen/logrus"
28 //go:embed config.default.yml
29 var DefaultYAML []byte
31 var ErrNoClustersDefined = errors.New("config does not define any clusters")
35 Logger logrus.FieldLogger
36 SkipDeprecated bool // Don't load deprecated config keys
37 SkipLegacy bool // Don't load legacy config files
38 SkipAPICalls bool // Don't do checks that call RailsAPI/controller
43 CrunchDispatchSlurmPath string
47 KeepBalancePath string
50 // UTC time for configdata: either the modtime of the file we
51 // read configdata from, or the time when we read configdata
53 sourceTimestamp time.Time
56 // NewLoader returns a new Loader with Stdin and Logger set to the
57 // given values, and all config paths set to their default values.
58 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
59 ldr := &Loader{Stdin: stdin, Logger: logger}
60 // Calling SetupFlags on a throwaway FlagSet has the side
61 // effect of assigning default values to the configurable
63 ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
67 // SetupFlags configures a flagset so arguments like -config X can be
68 // used to change the loader's Path fields.
70 // ldr := NewLoader(os.Stdin, logrus.New())
71 // flagset := flag.NewFlagSet("", flag.ContinueOnError)
72 // ldr.SetupFlags(flagset)
73 // // ldr.Path == "/etc/arvados/config.yml"
74 // flagset.Parse([]string{"-config", "/tmp/c.yaml"})
75 // // ldr.Path == "/tmp/c.yaml"
76 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
77 flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
79 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
80 flagset.StringVar(&ldr.KeepWebPath, "legacy-keepweb-config", defaultKeepWebConfigPath, "Legacy keep-web configuration `file`")
81 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
82 flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
83 flagset.StringVar(&ldr.KeepproxyPath, "legacy-keepproxy-config", defaultKeepproxyConfigPath, "Legacy keepproxy configuration `file`")
84 flagset.StringVar(&ldr.GitHttpdPath, "legacy-git-httpd-config", defaultGitHttpdConfigPath, "Legacy arv-git-httpd configuration `file`")
85 flagset.StringVar(&ldr.KeepBalancePath, "legacy-keepbalance-config", defaultKeepBalanceConfigPath, "Legacy keep-balance configuration `file`")
86 flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
90 // MungeLegacyConfigArgs checks args for a -config flag whose argument
91 // is a regular file (or a symlink to one), but doesn't have a
92 // top-level "Clusters" key and therefore isn't a valid cluster
93 // configuration file. If it finds such a flag, it replaces -config
94 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
96 // This is used by programs that still need to accept "-config" as a
97 // way to specify a per-component config file until their config has
100 // If any errors are encountered while reading or parsing a config
101 // file, the given args are not munged. We presume the same errors
102 // will be encountered again and reported later on when trying to load
103 // cluster configuration from the same file, regardless of which
104 // struct we end up using.
105 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
106 munged := append([]string(nil), args...)
107 for i := 0; i < len(args); i++ {
108 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
112 if strings.Contains(args[i], "=") {
113 operand = strings.SplitN(args[i], "=", 2)[1]
114 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
120 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
123 f, err := os.Open(operand)
128 buf, err := ioutil.ReadAll(f)
132 var cfg arvados.Config
133 err = yaml.Unmarshal(buf, &cfg)
137 if len(cfg.Clusters) == 0 {
138 lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
139 if operand == args[i] {
140 munged[i-1] = legacyConfigArg
142 munged[i] = legacyConfigArg + "=" + operand
147 // Disable legacy config loading for components other than the
148 // one that was specified
149 if legacyConfigArg != "-legacy-keepstore-config" {
150 ldr.KeepstorePath = ""
152 if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
153 ldr.CrunchDispatchSlurmPath = ""
155 if legacyConfigArg != "-legacy-ws-config" {
156 ldr.WebsocketPath = ""
158 if legacyConfigArg != "-legacy-keepweb-config" {
161 if legacyConfigArg != "-legacy-keepproxy-config" {
162 ldr.KeepproxyPath = ""
164 if legacyConfigArg != "-legacy-git-httpd-config" {
165 ldr.GitHttpdPath = ""
167 if legacyConfigArg != "-legacy-keepbalance-config" {
168 ldr.KeepBalancePath = ""
174 func (ldr *Loader) loadBytes(path string) ([]byte, time.Time, error) {
176 buf, err := ioutil.ReadAll(ldr.Stdin)
177 return buf, time.Now().UTC(), err
179 f, err := os.Open(path)
181 return nil, time.Time{}, err
186 return nil, time.Time{}, err
188 buf, err := ioutil.ReadAll(f)
189 return buf, fi.ModTime().UTC(), err
192 func (ldr *Loader) Load() (*arvados.Config, error) {
193 if ldr.configdata == nil {
194 buf, t, err := ldr.loadBytes(ldr.Path)
199 ldr.sourceTimestamp = t
202 // FIXME: We should reject YAML if the same key is used twice
203 // in a map/object, like {foo: bar, foo: baz}. Maybe we'll get
204 // this fixed free when we upgrade ghodss/yaml to a version
205 // that uses go-yaml v3.
207 // Load the config into a dummy map to get the cluster ID
208 // keys, discarding the values; then set up defaults for each
209 // cluster ID; then load the real config on top of the
212 Clusters map[string]struct{}
214 err := yaml.Unmarshal(ldr.configdata, &dummy)
218 if len(dummy.Clusters) == 0 {
219 return nil, ErrNoClustersDefined
222 // We can't merge deep structs here; instead, we unmarshal the
223 // default & loaded config files into generic maps, merge
224 // those, and then json-encode+decode the result into the
225 // config struct type.
226 var merged map[string]interface{}
227 for id := range dummy.Clusters {
228 var src map[string]interface{}
229 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
231 return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
233 err = mergo.Merge(&merged, src, mergo.WithOverride)
235 return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
238 var src map[string]interface{}
239 err = yaml.Unmarshal(ldr.configdata, &src)
241 return nil, fmt.Errorf("loading config data: %s", err)
243 ldr.logExtraKeys(merged, src, "")
244 removeSampleKeys(merged)
245 // We merge the loaded config into the default, overriding any existing keys.
246 // Make sure we do not override a default with a key that has a 'null' value.
248 err = mergo.Merge(&merged, src, mergo.WithOverride)
250 return nil, fmt.Errorf("merging config data: %s", err)
253 // map[string]interface{} => json => arvados.Config
254 var cfg arvados.Config
258 errEnc = json.NewEncoder(pw).Encode(merged)
261 err = json.NewDecoder(pr).Decode(&cfg)
266 return nil, fmt.Errorf("transcoding config data: %s", err)
269 var loadFuncs []func(*arvados.Config) error
270 if !ldr.SkipDeprecated {
271 loadFuncs = append(loadFuncs,
272 ldr.applyDeprecatedConfig,
273 ldr.applyDeprecatedVolumeDriverParameters,
277 // legacy file is required when either:
278 // * a non-default location was specified
279 // * no primary config was loaded, and this is the
280 // legacy config file for the current component
281 loadFuncs = append(loadFuncs,
282 ldr.loadOldEnvironmentVariables,
283 ldr.loadOldKeepstoreConfig,
284 ldr.loadOldKeepWebConfig,
285 ldr.loadOldCrunchDispatchSlurmConfig,
286 ldr.loadOldWebsocketConfig,
287 ldr.loadOldKeepproxyConfig,
288 ldr.loadOldGitHttpdConfig,
289 ldr.loadOldKeepBalanceConfig,
292 loadFuncs = append(loadFuncs, ldr.setImplicitStorageClasses)
293 for _, f := range loadFuncs {
300 // Preprocess/automate some configs
301 for id, cc := range cfg.Clusters {
302 ldr.autofillPreemptible("Clusters."+id, &cc)
304 if strings.Count(cc.Users.AnonymousUserToken, "/") == 3 {
305 // V2 token, strip it to just a secret
306 tmp := strings.Split(cc.Users.AnonymousUserToken, "/")
307 cc.Users.AnonymousUserToken = tmp[2]
310 cfg.Clusters[id] = cc
313 // Check for known mistakes
314 for id, cc := range cfg.Clusters {
315 for remote := range cc.RemoteClusters {
316 if remote == "*" || remote == "SAMPLE" {
319 err = ldr.checkClusterID(fmt.Sprintf("Clusters.%s.RemoteClusters.%s", id, remote), remote, true)
324 for _, err = range []error{
325 ldr.checkClusterID(fmt.Sprintf("Clusters.%s", id), id, false),
326 ldr.checkClusterID(fmt.Sprintf("Clusters.%s.Login.LoginCluster", id), cc.Login.LoginCluster, true),
327 ldr.checkToken(fmt.Sprintf("Clusters.%s.ManagementToken", id), cc.ManagementToken, true, false),
328 ldr.checkToken(fmt.Sprintf("Clusters.%s.SystemRootToken", id), cc.SystemRootToken, true, false),
329 ldr.checkToken(fmt.Sprintf("Clusters.%s.Users.AnonymousUserToken", id), cc.Users.AnonymousUserToken, false, true),
330 ldr.checkToken(fmt.Sprintf("Clusters.%s.Collections.BlobSigningKey", id), cc.Collections.BlobSigningKey, true, false),
331 checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection),
332 ldr.checkEnum("Containers.LocalKeepLogsToContainerLog", cc.Containers.LocalKeepLogsToContainerLog, "none", "all", "errors"),
333 ldr.checkEmptyKeepstores(cc),
334 ldr.checkUnlistedKeepstores(cc),
335 ldr.checkStorageClasses(cc),
336 ldr.checkCUDAVersions(cc),
337 // TODO: check non-empty Rendezvous on
338 // services other than Keepstore
345 cfg.SourceTimestamp = ldr.sourceTimestamp
346 cfg.SourceSHA256 = fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
350 var acceptableClusterIDRe = regexp.MustCompile(`^[a-z0-9]{5}$`)
352 func (ldr *Loader) checkClusterID(label, clusterID string, emptyStringOk bool) error {
353 if emptyStringOk && clusterID == "" {
355 } else if !acceptableClusterIDRe.MatchString(clusterID) {
356 return fmt.Errorf("%s: cluster ID should be 5 alphanumeric characters", label)
361 var acceptableTokenRe = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
362 var acceptableTokenLength = 32
364 func (ldr *Loader) checkToken(label, token string, mandatory bool, acceptV2 bool) error {
367 // when a token is not mandatory, the acceptable length and content is only checked if its length is non-zero
370 if ldr.Logger != nil {
371 ldr.Logger.Warnf("%s: secret token is not set (use %d+ random characters from a-z, A-Z, 0-9)", label, acceptableTokenLength)
374 } else if !acceptableTokenRe.MatchString(token) {
376 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
378 // Test for a proper V2 token
379 tmp := strings.SplitN(token, "/", 3)
381 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
383 if !strings.HasPrefix(token, "v2/") {
384 return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
386 if !acceptableTokenRe.MatchString(tmp[2]) {
387 return fmt.Errorf("%s: unacceptable characters in V2 token secret (only a-z, A-Z, 0-9 are acceptable)", label)
389 if len(tmp[2]) < acceptableTokenLength {
390 ldr.Logger.Warnf("%s: secret is too short (should be at least %d characters)", label, acceptableTokenLength)
392 } else if len(token) < acceptableTokenLength {
393 if ldr.Logger != nil {
394 ldr.Logger.Warnf("%s: token is too short (should be at least %d characters)", label, acceptableTokenLength)
400 func (ldr *Loader) checkEnum(label, value string, accepted ...string) error {
401 for _, s := range accepted {
406 return fmt.Errorf("%s: unacceptable value %q: must be one of %q", label, value, accepted)
409 func (ldr *Loader) setImplicitStorageClasses(cfg *arvados.Config) error {
411 for id, cc := range cfg.Clusters {
412 if len(cc.StorageClasses) > 0 {
415 for _, vol := range cc.Volumes {
416 if len(vol.StorageClasses) > 0 {
420 // No explicit StorageClasses config info at all; fill
421 // in implicit defaults.
422 for id, vol := range cc.Volumes {
423 vol.StorageClasses = map[string]bool{"default": true}
426 cc.StorageClasses = map[string]arvados.StorageClassConfig{"default": {Default: true}}
427 cfg.Clusters[id] = cc
432 func (ldr *Loader) checkStorageClasses(cc arvados.Cluster) error {
433 classOnVolume := map[string]bool{}
434 for volid, vol := range cc.Volumes {
435 if len(vol.StorageClasses) == 0 {
436 return fmt.Errorf("%s: volume has no StorageClasses listed", volid)
438 for classid := range vol.StorageClasses {
439 if _, ok := cc.StorageClasses[classid]; !ok {
440 return fmt.Errorf("%s: volume refers to storage class %q that is not defined in StorageClasses", volid, classid)
442 classOnVolume[classid] = true
446 for classid, sc := range cc.StorageClasses {
447 if !classOnVolume[classid] && len(cc.Volumes) > 0 {
448 ldr.Logger.Warnf("there are no volumes providing storage class %q", classid)
455 return fmt.Errorf("there is no default storage class (at least one entry in StorageClasses must have Default: true)")
460 func (ldr *Loader) checkCUDAVersions(cc arvados.Cluster) error {
461 for _, it := range cc.InstanceTypes {
462 if it.CUDA.DeviceCount == 0 {
466 _, err := strconv.ParseFloat(it.CUDA.DriverVersion, 64)
468 return fmt.Errorf("InstanceType %q has invalid CUDA.DriverVersion %q, expected format X.Y (%v)", it.Name, it.CUDA.DriverVersion, err)
470 _, err = strconv.ParseFloat(it.CUDA.HardwareCapability, 64)
472 return fmt.Errorf("InstanceType %q has invalid CUDA.HardwareCapability %q, expected format X.Y (%v)", it.Name, it.CUDA.HardwareCapability, err)
478 func checkKeyConflict(label string, m map[string]string) error {
479 saw := map[string]bool{}
481 k = strings.ToLower(k)
483 return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
490 func removeNullKeys(m map[string]interface{}) {
491 for k, v := range m {
495 if v, _ := v.(map[string]interface{}); v != nil {
501 func removeSampleKeys(m map[string]interface{}) {
503 for _, v := range m {
504 if v, _ := v.(map[string]interface{}); v != nil {
510 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
511 if ldr.Logger == nil {
514 for k, vsupp := range supplied {
516 // entry will be dropped in removeSampleKeys anyway
519 vexp, ok := expected[k]
520 if expected["SAMPLE"] != nil {
521 // use the SAMPLE entry's keys as the
522 // "expected" map when checking vsupp
524 vexp = expected["SAMPLE"]
526 // check for a case-insensitive match
528 for ek := range expected {
529 if strings.EqualFold(k, ek) {
530 hint = " (perhaps you meant " + ek + "?)"
531 // If we don't delete this, it
532 // will end up getting merged,
534 // merging/overriding the
540 ldr.Logger.Warnf("deprecated or unknown config entry: %s%s%s", prefix, k, hint)
543 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
544 // if vsupp is a map but vexp isn't map, this
545 // will be caught elsewhere; see TestBadType.
547 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
548 ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
550 ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
555 func (ldr *Loader) autofillPreemptible(label string, cc *arvados.Cluster) {
556 if factor := cc.Containers.PreemptiblePriceFactor; factor > 0 {
557 for name, it := range cc.InstanceTypes {
559 it.Preemptible = true
560 it.Price = it.Price * factor
561 it.Name = name + ".preemptible"
562 if it2, exists := cc.InstanceTypes[it.Name]; exists && it2 != it {
563 ldr.Logger.Warnf("%s.InstanceTypes[%s]: already exists, so not automatically adding a preemptible variant of %s", label, it.Name, name)
566 cc.InstanceTypes[it.Name] = it