15370: Bump docker API version to 1.35.
[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.checkLocalKeepBlobBuffers(cc),
349                         ldr.checkStorageClasses(cc),
350                         ldr.checkCUDAVersions(cc),
351                         // TODO: check non-empty Rendezvous on
352                         // services other than Keepstore
353                 } {
354                         if err != nil {
355                                 return nil, err
356                         }
357                 }
358         }
359         cfg.SourceTimestamp = ldr.sourceTimestamp
360         cfg.SourceSHA256 = fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
361         return &cfg, nil
362 }
363
364 var acceptableClusterIDRe = regexp.MustCompile(`^[a-z0-9]{5}$`)
365
366 func (ldr *Loader) checkClusterID(label, clusterID string, emptyStringOk bool) error {
367         if emptyStringOk && clusterID == "" {
368                 return nil
369         } else if !acceptableClusterIDRe.MatchString(clusterID) {
370                 return fmt.Errorf("%s: cluster ID should be 5 alphanumeric characters", label)
371         }
372         return nil
373 }
374
375 var acceptableTokenRe = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
376 var acceptableTokenLength = 32
377
378 func (ldr *Loader) checkToken(label, token string, mandatory bool, acceptV2 bool) error {
379         if len(token) == 0 {
380                 if !mandatory {
381                         // when a token is not mandatory, the acceptable length and content is only checked if its length is non-zero
382                         return nil
383                 } else {
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)
386                         }
387                 }
388         } else if !acceptableTokenRe.MatchString(token) {
389                 if !acceptV2 {
390                         return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
391                 }
392                 // Test for a proper V2 token
393                 tmp := strings.SplitN(token, "/", 3)
394                 if len(tmp) != 3 {
395                         return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
396                 }
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)
399                 }
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)
402                 }
403                 if len(tmp[2]) < acceptableTokenLength {
404                         ldr.Logger.Warnf("%s: secret is too short (should be at least %d characters)", label, acceptableTokenLength)
405                 }
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)
409                 }
410         }
411         return nil
412 }
413
414 func (ldr *Loader) checkEnum(label, value string, accepted ...string) error {
415         for _, s := range accepted {
416                 if s == value {
417                         return nil
418                 }
419         }
420         return fmt.Errorf("%s: unacceptable value %q: must be one of %q", label, value, accepted)
421 }
422
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" {
426                         continue
427                 }
428                 if len(cc.InstanceTypes) == 1 {
429                         continue
430                 }
431                 if len(cc.InstanceTypes) > 1 {
432                         return fmt.Errorf("Clusters.%s.InstanceTypes: cannot use multiple InstanceTypes with loopback driver", id)
433                 }
434                 // No InstanceTypes configured. Fill in implicit
435                 // default.
436                 hostram, err := getHostRAM()
437                 if err != nil {
438                         return err
439                 }
440                 scratch, err := getFilesystemSize(os.TempDir())
441                 if err != nil {
442                         return err
443                 }
444                 cc.InstanceTypes = arvados.InstanceTypeMap{"localhost": {
445                         Name:            "localhost",
446                         ProviderType:    "localhost",
447                         VCPUs:           runtime.NumCPU(),
448                         RAM:             hostram,
449                         Scratch:         scratch,
450                         IncludedScratch: scratch,
451                 }}
452                 cfg.Clusters[id] = cc
453         }
454         return nil
455 }
456
457 func getFilesystemSize(path string) (arvados.ByteSize, error) {
458         var stat unix.Statfs_t
459         err := unix.Statfs(path, &stat)
460         if err != nil {
461                 return 0, err
462         }
463         return arvados.ByteSize(stat.Blocks * uint64(stat.Bsize)), nil
464 }
465
466 var reMemTotal = regexp.MustCompile(`(^|\n)MemTotal: *(\d+) kB\n`)
467
468 func getHostRAM() (arvados.ByteSize, error) {
469         buf, err := os.ReadFile("/proc/meminfo")
470         if err != nil {
471                 return 0, err
472         }
473         m := reMemTotal.FindSubmatch(buf)
474         if m == nil {
475                 return 0, errors.New("error parsing /proc/meminfo: no MemTotal")
476         }
477         kb, err := strconv.ParseInt(string(m[2]), 10, 64)
478         if err != nil {
479                 return 0, fmt.Errorf("error parsing /proc/meminfo: %q: %w", m[2], err)
480         }
481         return arvados.ByteSize(kb) * 1024, nil
482 }
483
484 func (ldr *Loader) setImplicitStorageClasses(cfg *arvados.Config) error {
485 cluster:
486         for id, cc := range cfg.Clusters {
487                 if len(cc.StorageClasses) > 0 {
488                         continue cluster
489                 }
490                 for _, vol := range cc.Volumes {
491                         if len(vol.StorageClasses) > 0 {
492                                 continue cluster
493                         }
494                 }
495                 // No explicit StorageClasses config info at all; fill
496                 // in implicit defaults.
497                 for id, vol := range cc.Volumes {
498                         vol.StorageClasses = map[string]bool{"default": true}
499                         cc.Volumes[id] = vol
500                 }
501                 cc.StorageClasses = map[string]arvados.StorageClassConfig{"default": {Default: true}}
502                 cfg.Clusters[id] = cc
503         }
504         return nil
505 }
506
507 func (ldr *Loader) checkLocalKeepBlobBuffers(cc arvados.Cluster) error {
508         kbb := cc.Containers.LocalKeepBlobBuffersPerVCPU
509         if kbb == 0 {
510                 return nil
511         }
512         for uuid, vol := range cc.Volumes {
513                 if len(vol.AccessViaHosts) > 0 {
514                         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)
515                         return nil
516                 }
517                 if !vol.ReadOnly && vol.Replication < cc.Collections.DefaultReplication {
518                         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)
519                         return nil
520                 }
521         }
522         return nil
523 }
524
525 func (ldr *Loader) checkStorageClasses(cc arvados.Cluster) error {
526         classOnVolume := map[string]bool{}
527         for volid, vol := range cc.Volumes {
528                 if len(vol.StorageClasses) == 0 {
529                         return fmt.Errorf("%s: volume has no StorageClasses listed", volid)
530                 }
531                 for classid := range vol.StorageClasses {
532                         if _, ok := cc.StorageClasses[classid]; !ok {
533                                 return fmt.Errorf("%s: volume refers to storage class %q that is not defined in StorageClasses", volid, classid)
534                         }
535                         classOnVolume[classid] = true
536                 }
537         }
538         haveDefault := false
539         for classid, sc := range cc.StorageClasses {
540                 if !classOnVolume[classid] && len(cc.Volumes) > 0 {
541                         ldr.Logger.Warnf("there are no volumes providing storage class %q", classid)
542                 }
543                 if sc.Default {
544                         haveDefault = true
545                 }
546         }
547         if !haveDefault {
548                 return fmt.Errorf("there is no default storage class (at least one entry in StorageClasses must have Default: true)")
549         }
550         return nil
551 }
552
553 func (ldr *Loader) checkCUDAVersions(cc arvados.Cluster) error {
554         for _, it := range cc.InstanceTypes {
555                 if it.CUDA.DeviceCount == 0 {
556                         continue
557                 }
558
559                 _, err := strconv.ParseFloat(it.CUDA.DriverVersion, 64)
560                 if err != nil {
561                         return fmt.Errorf("InstanceType %q has invalid CUDA.DriverVersion %q, expected format X.Y (%v)", it.Name, it.CUDA.DriverVersion, err)
562                 }
563                 _, err = strconv.ParseFloat(it.CUDA.HardwareCapability, 64)
564                 if err != nil {
565                         return fmt.Errorf("InstanceType %q has invalid CUDA.HardwareCapability %q, expected format X.Y (%v)", it.Name, it.CUDA.HardwareCapability, err)
566                 }
567         }
568         return nil
569 }
570
571 func checkKeyConflict(label string, m map[string]string) error {
572         saw := map[string]bool{}
573         for k := range m {
574                 k = strings.ToLower(k)
575                 if saw[k] {
576                         return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
577                 }
578                 saw[k] = true
579         }
580         return nil
581 }
582
583 func removeNullKeys(m map[string]interface{}) {
584         for k, v := range m {
585                 if v == nil {
586                         delete(m, k)
587                 }
588                 if v, _ := v.(map[string]interface{}); v != nil {
589                         removeNullKeys(v)
590                 }
591         }
592 }
593
594 func removeSampleKeys(m map[string]interface{}) {
595         delete(m, "SAMPLE")
596         for _, v := range m {
597                 if v, _ := v.(map[string]interface{}); v != nil {
598                         removeSampleKeys(v)
599                 }
600         }
601 }
602
603 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
604         if ldr.Logger == nil {
605                 return
606         }
607         for k, vsupp := range supplied {
608                 if k == "SAMPLE" {
609                         // entry will be dropped in removeSampleKeys anyway
610                         continue
611                 }
612                 vexp, ok := expected[k]
613                 if expected["SAMPLE"] != nil {
614                         // use the SAMPLE entry's keys as the
615                         // "expected" map when checking vsupp
616                         // recursively.
617                         vexp = expected["SAMPLE"]
618                 } else if !ok {
619                         // check for a case-insensitive match
620                         hint := ""
621                         for ek := range expected {
622                                 if strings.EqualFold(k, ek) {
623                                         hint = " (perhaps you meant " + ek + "?)"
624                                         // If we don't delete this, it
625                                         // will end up getting merged,
626                                         // unpredictably
627                                         // merging/overriding the
628                                         // default.
629                                         delete(supplied, k)
630                                         break
631                                 }
632                         }
633                         ldr.Logger.Warnf("deprecated or unknown config entry: %s%s%s", prefix, k, hint)
634                         continue
635                 }
636                 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
637                         // if vsupp is a map but vexp isn't map, this
638                         // will be caught elsewhere; see TestBadType.
639                         continue
640                 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
641                         ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
642                 } else {
643                         ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
644                 }
645         }
646 }
647
648 func (ldr *Loader) autofillPreemptible(label string, cc *arvados.Cluster) {
649         if factor := cc.Containers.PreemptiblePriceFactor; factor > 0 {
650                 for name, it := range cc.InstanceTypes {
651                         if !it.Preemptible {
652                                 it.Preemptible = true
653                                 it.Price = it.Price * factor
654                                 it.Name = name + ".preemptible"
655                                 if it2, exists := cc.InstanceTypes[it.Name]; exists && it2 != it {
656                                         ldr.Logger.Warnf("%s.InstanceTypes[%s]: already exists, so not automatically adding a preemptible variant of %s", label, it.Name, name)
657                                         continue
658                                 }
659                                 cc.InstanceTypes[it.Name] = it
660                         }
661                 }
662         }
663
664 }
665
666 // RegisterMetrics registers metrics showing the timestamp and content
667 // hash of the currently loaded config.
668 //
669 // Must not be called more than once for a given registry. Must not be
670 // called before Load(). Metrics are not updated by subsequent calls
671 // to Load().
672 func (ldr *Loader) RegisterMetrics(reg *prometheus.Registry) {
673         hash := fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
674         vec := prometheus.NewGaugeVec(prometheus.GaugeOpts{
675                 Namespace: "arvados",
676                 Subsystem: "config",
677                 Name:      "source_timestamp_seconds",
678                 Help:      "Timestamp of config file when it was loaded.",
679         }, []string{"sha256"})
680         vec.WithLabelValues(hash).Set(float64(ldr.sourceTimestamp.UnixNano()) / 1e9)
681         reg.MustRegister(vec)
682
683         vec = prometheus.NewGaugeVec(prometheus.GaugeOpts{
684                 Namespace: "arvados",
685                 Subsystem: "config",
686                 Name:      "load_timestamp_seconds",
687                 Help:      "Time when config file was loaded.",
688         }, []string{"sha256"})
689         vec.WithLabelValues(hash).Set(float64(ldr.loadTimestamp.UnixNano()) / 1e9)
690         reg.MustRegister(vec)
691 }