15370: Merge branch 'main' into 15370-loopback-dispatchcloud
[arvados.git] / lib / config / load.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package config
6
7 import (
8         "bytes"
9         "crypto/sha256"
10         _ "embed"
11         "encoding/json"
12         "errors"
13         "flag"
14         "fmt"
15         "io"
16         "io/ioutil"
17         "os"
18         "regexp"
19         "runtime"
20         "strconv"
21         "strings"
22         "time"
23
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"
30 )
31
32 //go:embed config.default.yml
33 var DefaultYAML []byte
34
35 var ErrNoClustersDefined = errors.New("config does not define any clusters")
36
37 type Loader struct {
38         Stdin          io.Reader
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
43
44         Path                    string
45         KeepstorePath           string
46         KeepWebPath             string
47         CrunchDispatchSlurmPath string
48         WebsocketPath           string
49         KeepproxyPath           string
50         GitHttpdPath            string
51         KeepBalancePath         string
52
53         configdata []byte
54         // UTC time for configdata: either the modtime of the file we
55         // read configdata from, or the time when we read configdata
56         // from a pipe.
57         sourceTimestamp time.Time
58         // UTC time when configdata was read.
59         loadTimestamp time.Time
60 }
61
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
68         // fields.
69         ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
70         return ldr
71 }
72
73 // SetupFlags configures a flagset so arguments like -config X can be
74 // used to change the loader's Path fields.
75 //
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)")
84         if !ldr.SkipLegacy {
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")
93         }
94 }
95
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").
101 //
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
104 // been migrated.
105 //
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" {
115                         continue
116                 }
117                 var operand string
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], "-") {
121                         i++
122                         operand = args[i]
123                 } else {
124                         continue
125                 }
126                 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
127                         continue
128                 }
129                 f, err := os.Open(operand)
130                 if err != nil {
131                         continue
132                 }
133                 defer f.Close()
134                 buf, err := ioutil.ReadAll(f)
135                 if err != nil {
136                         continue
137                 }
138                 var cfg arvados.Config
139                 err = yaml.Unmarshal(buf, &cfg)
140                 if err != nil {
141                         continue
142                 }
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
147                         } else {
148                                 munged[i] = legacyConfigArg + "=" + operand
149                         }
150                 }
151         }
152
153         // Disable legacy config loading for components other than the
154         // one that was specified
155         if legacyConfigArg != "-legacy-keepstore-config" {
156                 ldr.KeepstorePath = ""
157         }
158         if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
159                 ldr.CrunchDispatchSlurmPath = ""
160         }
161         if legacyConfigArg != "-legacy-ws-config" {
162                 ldr.WebsocketPath = ""
163         }
164         if legacyConfigArg != "-legacy-keepweb-config" {
165                 ldr.KeepWebPath = ""
166         }
167         if legacyConfigArg != "-legacy-keepproxy-config" {
168                 ldr.KeepproxyPath = ""
169         }
170         if legacyConfigArg != "-legacy-git-httpd-config" {
171                 ldr.GitHttpdPath = ""
172         }
173         if legacyConfigArg != "-legacy-keepbalance-config" {
174                 ldr.KeepBalancePath = ""
175         }
176
177         return munged
178 }
179
180 func (ldr *Loader) loadBytes(path string) (buf []byte, sourceTime, loadTime time.Time, err error) {
181         loadTime = time.Now().UTC()
182         if path == "-" {
183                 buf, err = ioutil.ReadAll(ldr.Stdin)
184                 sourceTime = loadTime
185                 return
186         }
187         f, err := os.Open(path)
188         if err != nil {
189                 return
190         }
191         defer f.Close()
192         fi, err := f.Stat()
193         if err != nil {
194                 return
195         }
196         sourceTime = fi.ModTime().UTC()
197         buf, err = ioutil.ReadAll(f)
198         return
199 }
200
201 func (ldr *Loader) Load() (*arvados.Config, error) {
202         if ldr.configdata == nil {
203                 buf, sourceTime, loadTime, err := ldr.loadBytes(ldr.Path)
204                 if err != nil {
205                         return nil, err
206                 }
207                 ldr.configdata = buf
208                 ldr.sourceTimestamp = sourceTime
209                 ldr.loadTimestamp = loadTime
210         }
211
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.
216
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
220         // defaults.
221         var dummy struct {
222                 Clusters map[string]struct{}
223         }
224         err := yaml.Unmarshal(ldr.configdata, &dummy)
225         if err != nil {
226                 return nil, err
227         }
228         if len(dummy.Clusters) == 0 {
229                 return nil, ErrNoClustersDefined
230         }
231
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)
240                 if err != nil {
241                         return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
242                 }
243                 err = mergo.Merge(&merged, src, mergo.WithOverride)
244                 if err != nil {
245                         return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
246                 }
247         }
248         var src map[string]interface{}
249         err = yaml.Unmarshal(ldr.configdata, &src)
250         if err != nil {
251                 return nil, fmt.Errorf("loading config data: %s", err)
252         }
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.
257         removeNullKeys(src)
258         err = mergo.Merge(&merged, src, mergo.WithOverride)
259         if err != nil {
260                 return nil, fmt.Errorf("merging config data: %s", err)
261         }
262
263         // map[string]interface{} => json => arvados.Config
264         var cfg arvados.Config
265         var errEnc error
266         pr, pw := io.Pipe()
267         go func() {
268                 errEnc = json.NewEncoder(pw).Encode(merged)
269                 pw.Close()
270         }()
271         err = json.NewDecoder(pr).Decode(&cfg)
272         if errEnc != nil {
273                 err = errEnc
274         }
275         if err != nil {
276                 return nil, fmt.Errorf("transcoding config data: %s", err)
277         }
278
279         var loadFuncs []func(*arvados.Config) error
280         if !ldr.SkipDeprecated {
281                 loadFuncs = append(loadFuncs,
282                         ldr.applyDeprecatedConfig,
283                         ldr.applyDeprecatedVolumeDriverParameters,
284                 )
285         }
286         if !ldr.SkipLegacy {
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,
300                 )
301         }
302         loadFuncs = append(loadFuncs,
303                 ldr.setImplicitStorageClasses,
304                 ldr.setLoopbackInstanceType,
305         )
306         for _, f := range loadFuncs {
307                 err = f(&cfg)
308                 if err != nil {
309                         return nil, err
310                 }
311         }
312
313         // Preprocess/automate some configs
314         for id, cc := range cfg.Clusters {
315                 ldr.autofillPreemptible("Clusters."+id, &cc)
316
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]
321                 }
322
323                 cfg.Clusters[id] = cc
324         }
325
326         // Check for known mistakes
327         for id, cc := range cfg.Clusters {
328                 for remote := range cc.RemoteClusters {
329                         if remote == "*" || remote == "SAMPLE" {
330                                 continue
331                         }
332                         err = ldr.checkClusterID(fmt.Sprintf("Clusters.%s.RemoteClusters.%s", id, remote), remote, true)
333                         if err != nil {
334                                 return nil, err
335                         }
336                 }
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.checkStorageClasses(cc),
349                         ldr.checkCUDAVersions(cc),
350                         // TODO: check non-empty Rendezvous on
351                         // services other than Keepstore
352                 } {
353                         if err != nil {
354                                 return nil, err
355                         }
356                 }
357         }
358         cfg.SourceTimestamp = ldr.sourceTimestamp
359         cfg.SourceSHA256 = fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
360         return &cfg, nil
361 }
362
363 var acceptableClusterIDRe = regexp.MustCompile(`^[a-z0-9]{5}$`)
364
365 func (ldr *Loader) checkClusterID(label, clusterID string, emptyStringOk bool) error {
366         if emptyStringOk && clusterID == "" {
367                 return nil
368         } else if !acceptableClusterIDRe.MatchString(clusterID) {
369                 return fmt.Errorf("%s: cluster ID should be 5 alphanumeric characters", label)
370         }
371         return nil
372 }
373
374 var acceptableTokenRe = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
375 var acceptableTokenLength = 32
376
377 func (ldr *Loader) checkToken(label, token string, mandatory bool, acceptV2 bool) error {
378         if len(token) == 0 {
379                 if !mandatory {
380                         // when a token is not mandatory, the acceptable length and content is only checked if its length is non-zero
381                         return nil
382                 } else {
383                         if ldr.Logger != nil {
384                                 ldr.Logger.Warnf("%s: secret token is not set (use %d+ random characters from a-z, A-Z, 0-9)", label, acceptableTokenLength)
385                         }
386                 }
387         } else if !acceptableTokenRe.MatchString(token) {
388                 if !acceptV2 {
389                         return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
390                 }
391                 // Test for a proper V2 token
392                 tmp := strings.SplitN(token, "/", 3)
393                 if len(tmp) != 3 {
394                         return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
395                 }
396                 if !strings.HasPrefix(token, "v2/") {
397                         return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
398                 }
399                 if !acceptableTokenRe.MatchString(tmp[2]) {
400                         return fmt.Errorf("%s: unacceptable characters in V2 token secret (only a-z, A-Z, 0-9 are acceptable)", label)
401                 }
402                 if len(tmp[2]) < acceptableTokenLength {
403                         ldr.Logger.Warnf("%s: secret is too short (should be at least %d characters)", label, acceptableTokenLength)
404                 }
405         } else if len(token) < acceptableTokenLength {
406                 if ldr.Logger != nil {
407                         ldr.Logger.Warnf("%s: token is too short (should be at least %d characters)", label, acceptableTokenLength)
408                 }
409         }
410         return nil
411 }
412
413 func (ldr *Loader) checkEnum(label, value string, accepted ...string) error {
414         for _, s := range accepted {
415                 if s == value {
416                         return nil
417                 }
418         }
419         return fmt.Errorf("%s: unacceptable value %q: must be one of %q", label, value, accepted)
420 }
421
422 func (ldr *Loader) setLoopbackInstanceType(cfg *arvados.Config) error {
423         for id, cc := range cfg.Clusters {
424                 if !cc.Containers.CloudVMs.Enable || cc.Containers.CloudVMs.Driver != "loopback" {
425                         continue
426                 }
427                 if len(cc.InstanceTypes) == 1 {
428                         continue
429                 }
430                 if len(cc.InstanceTypes) > 1 {
431                         return fmt.Errorf("Clusters.%s.InstanceTypes: cannot use multiple InstanceTypes with loopback driver", id)
432                 }
433                 // No InstanceTypes configured. Fill in implicit
434                 // default.
435                 hostram, err := getHostRAM()
436                 if err != nil {
437                         return err
438                 }
439                 scratch, err := getFilesystemSize(os.TempDir())
440                 if err != nil {
441                         return err
442                 }
443                 cc.InstanceTypes = arvados.InstanceTypeMap{"localhost": {
444                         Name:            "localhost",
445                         ProviderType:    "localhost",
446                         VCPUs:           runtime.NumCPU(),
447                         RAM:             hostram,
448                         Scratch:         scratch,
449                         IncludedScratch: scratch,
450                 }}
451                 cfg.Clusters[id] = cc
452         }
453         return nil
454 }
455
456 func getFilesystemSize(path string) (arvados.ByteSize, error) {
457         var stat unix.Statfs_t
458         err := unix.Statfs(path, &stat)
459         if err != nil {
460                 return 0, err
461         }
462         return arvados.ByteSize(stat.Blocks * uint64(stat.Bsize)), nil
463 }
464
465 var reMemTotal = regexp.MustCompile(`(^|\n)MemTotal: *(\d+) kB\n`)
466
467 func getHostRAM() (arvados.ByteSize, error) {
468         buf, err := os.ReadFile("/proc/meminfo")
469         if err != nil {
470                 return 0, err
471         }
472         m := reMemTotal.FindSubmatch(buf)
473         if m == nil {
474                 return 0, errors.New("error parsing /proc/meminfo: no MemTotal")
475         }
476         kb, err := strconv.ParseInt(string(m[2]), 10, 64)
477         if err != nil {
478                 return 0, fmt.Errorf("error parsing /proc/meminfo: %q: %w", m[2], err)
479         }
480         return arvados.ByteSize(kb) * 1024, nil
481 }
482
483 func (ldr *Loader) setImplicitStorageClasses(cfg *arvados.Config) error {
484 cluster:
485         for id, cc := range cfg.Clusters {
486                 if len(cc.StorageClasses) > 0 {
487                         continue cluster
488                 }
489                 for _, vol := range cc.Volumes {
490                         if len(vol.StorageClasses) > 0 {
491                                 continue cluster
492                         }
493                 }
494                 // No explicit StorageClasses config info at all; fill
495                 // in implicit defaults.
496                 for id, vol := range cc.Volumes {
497                         vol.StorageClasses = map[string]bool{"default": true}
498                         cc.Volumes[id] = vol
499                 }
500                 cc.StorageClasses = map[string]arvados.StorageClassConfig{"default": {Default: true}}
501                 cfg.Clusters[id] = cc
502         }
503         return nil
504 }
505
506 func (ldr *Loader) checkStorageClasses(cc arvados.Cluster) error {
507         classOnVolume := map[string]bool{}
508         for volid, vol := range cc.Volumes {
509                 if len(vol.StorageClasses) == 0 {
510                         return fmt.Errorf("%s: volume has no StorageClasses listed", volid)
511                 }
512                 for classid := range vol.StorageClasses {
513                         if _, ok := cc.StorageClasses[classid]; !ok {
514                                 return fmt.Errorf("%s: volume refers to storage class %q that is not defined in StorageClasses", volid, classid)
515                         }
516                         classOnVolume[classid] = true
517                 }
518         }
519         haveDefault := false
520         for classid, sc := range cc.StorageClasses {
521                 if !classOnVolume[classid] && len(cc.Volumes) > 0 {
522                         ldr.Logger.Warnf("there are no volumes providing storage class %q", classid)
523                 }
524                 if sc.Default {
525                         haveDefault = true
526                 }
527         }
528         if !haveDefault {
529                 return fmt.Errorf("there is no default storage class (at least one entry in StorageClasses must have Default: true)")
530         }
531         return nil
532 }
533
534 func (ldr *Loader) checkCUDAVersions(cc arvados.Cluster) error {
535         for _, it := range cc.InstanceTypes {
536                 if it.CUDA.DeviceCount == 0 {
537                         continue
538                 }
539
540                 _, err := strconv.ParseFloat(it.CUDA.DriverVersion, 64)
541                 if err != nil {
542                         return fmt.Errorf("InstanceType %q has invalid CUDA.DriverVersion %q, expected format X.Y (%v)", it.Name, it.CUDA.DriverVersion, err)
543                 }
544                 _, err = strconv.ParseFloat(it.CUDA.HardwareCapability, 64)
545                 if err != nil {
546                         return fmt.Errorf("InstanceType %q has invalid CUDA.HardwareCapability %q, expected format X.Y (%v)", it.Name, it.CUDA.HardwareCapability, err)
547                 }
548         }
549         return nil
550 }
551
552 func checkKeyConflict(label string, m map[string]string) error {
553         saw := map[string]bool{}
554         for k := range m {
555                 k = strings.ToLower(k)
556                 if saw[k] {
557                         return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
558                 }
559                 saw[k] = true
560         }
561         return nil
562 }
563
564 func removeNullKeys(m map[string]interface{}) {
565         for k, v := range m {
566                 if v == nil {
567                         delete(m, k)
568                 }
569                 if v, _ := v.(map[string]interface{}); v != nil {
570                         removeNullKeys(v)
571                 }
572         }
573 }
574
575 func removeSampleKeys(m map[string]interface{}) {
576         delete(m, "SAMPLE")
577         for _, v := range m {
578                 if v, _ := v.(map[string]interface{}); v != nil {
579                         removeSampleKeys(v)
580                 }
581         }
582 }
583
584 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
585         if ldr.Logger == nil {
586                 return
587         }
588         for k, vsupp := range supplied {
589                 if k == "SAMPLE" {
590                         // entry will be dropped in removeSampleKeys anyway
591                         continue
592                 }
593                 vexp, ok := expected[k]
594                 if expected["SAMPLE"] != nil {
595                         // use the SAMPLE entry's keys as the
596                         // "expected" map when checking vsupp
597                         // recursively.
598                         vexp = expected["SAMPLE"]
599                 } else if !ok {
600                         // check for a case-insensitive match
601                         hint := ""
602                         for ek := range expected {
603                                 if strings.EqualFold(k, ek) {
604                                         hint = " (perhaps you meant " + ek + "?)"
605                                         // If we don't delete this, it
606                                         // will end up getting merged,
607                                         // unpredictably
608                                         // merging/overriding the
609                                         // default.
610                                         delete(supplied, k)
611                                         break
612                                 }
613                         }
614                         ldr.Logger.Warnf("deprecated or unknown config entry: %s%s%s", prefix, k, hint)
615                         continue
616                 }
617                 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
618                         // if vsupp is a map but vexp isn't map, this
619                         // will be caught elsewhere; see TestBadType.
620                         continue
621                 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
622                         ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
623                 } else {
624                         ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
625                 }
626         }
627 }
628
629 func (ldr *Loader) autofillPreemptible(label string, cc *arvados.Cluster) {
630         if factor := cc.Containers.PreemptiblePriceFactor; factor > 0 {
631                 for name, it := range cc.InstanceTypes {
632                         if !it.Preemptible {
633                                 it.Preemptible = true
634                                 it.Price = it.Price * factor
635                                 it.Name = name + ".preemptible"
636                                 if it2, exists := cc.InstanceTypes[it.Name]; exists && it2 != it {
637                                         ldr.Logger.Warnf("%s.InstanceTypes[%s]: already exists, so not automatically adding a preemptible variant of %s", label, it.Name, name)
638                                         continue
639                                 }
640                                 cc.InstanceTypes[it.Name] = it
641                         }
642                 }
643         }
644
645 }
646
647 // RegisterMetrics registers metrics showing the timestamp and content
648 // hash of the currently loaded config.
649 //
650 // Must not be called more than once for a given registry. Must not be
651 // called before Load(). Metrics are not updated by subsequent calls
652 // to Load().
653 func (ldr *Loader) RegisterMetrics(reg *prometheus.Registry) {
654         hash := fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
655         vec := prometheus.NewGaugeVec(prometheus.GaugeOpts{
656                 Namespace: "arvados",
657                 Subsystem: "config",
658                 Name:      "source_timestamp_seconds",
659                 Help:      "Timestamp of config file when it was loaded.",
660         }, []string{"sha256"})
661         vec.WithLabelValues(hash).Set(float64(ldr.sourceTimestamp.UnixNano()) / 1e9)
662         reg.MustRegister(vec)
663
664         vec = prometheus.NewGaugeVec(prometheus.GaugeOpts{
665                 Namespace: "arvados",
666                 Subsystem: "config",
667                 Name:      "load_timestamp_seconds",
668                 Help:      "Time when config file was loaded.",
669         }, []string{"sha256"})
670         vec.WithLabelValues(hash).Set(float64(ldr.loadTimestamp.UnixNano()) / 1e9)
671         reg.MustRegister(vec)
672 }