dba799787045d732e3a07cb65859dc7bfa096c6d
[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         "strconv"
20         "strings"
21         "time"
22
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"
28 )
29
30 //go:embed config.default.yml
31 var DefaultYAML []byte
32
33 var ErrNoClustersDefined = errors.New("config does not define any clusters")
34
35 type Loader struct {
36         Stdin          io.Reader
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
41
42         Path                    string
43         KeepstorePath           string
44         KeepWebPath             string
45         CrunchDispatchSlurmPath string
46         WebsocketPath           string
47         KeepproxyPath           string
48         GitHttpdPath            string
49         KeepBalancePath         string
50
51         configdata []byte
52         // UTC time for configdata: either the modtime of the file we
53         // read configdata from, or the time when we read configdata
54         // from a pipe.
55         sourceTimestamp time.Time
56         // UTC time when configdata was read.
57         loadTimestamp time.Time
58 }
59
60 // NewLoader returns a new Loader with Stdin and Logger set to the
61 // given values, and all config paths set to their default values.
62 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
63         ldr := &Loader{Stdin: stdin, Logger: logger}
64         // Calling SetupFlags on a throwaway FlagSet has the side
65         // effect of assigning default values to the configurable
66         // fields.
67         ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
68         return ldr
69 }
70
71 // SetupFlags configures a flagset so arguments like -config X can be
72 // used to change the loader's Path fields.
73 //
74 //      ldr := NewLoader(os.Stdin, logrus.New())
75 //      flagset := flag.NewFlagSet("", flag.ContinueOnError)
76 //      ldr.SetupFlags(flagset)
77 //      // ldr.Path == "/etc/arvados/config.yml"
78 //      flagset.Parse([]string{"-config", "/tmp/c.yaml"})
79 //      // ldr.Path == "/tmp/c.yaml"
80 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
81         flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
82         if !ldr.SkipLegacy {
83                 flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
84                 flagset.StringVar(&ldr.KeepWebPath, "legacy-keepweb-config", defaultKeepWebConfigPath, "Legacy keep-web configuration `file`")
85                 flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
86                 flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
87                 flagset.StringVar(&ldr.KeepproxyPath, "legacy-keepproxy-config", defaultKeepproxyConfigPath, "Legacy keepproxy configuration `file`")
88                 flagset.StringVar(&ldr.GitHttpdPath, "legacy-git-httpd-config", defaultGitHttpdConfigPath, "Legacy arvados-git-httpd configuration `file`")
89                 flagset.StringVar(&ldr.KeepBalancePath, "legacy-keepbalance-config", defaultKeepBalanceConfigPath, "Legacy keep-balance configuration `file`")
90                 flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
91         }
92 }
93
94 // MungeLegacyConfigArgs checks args for a -config flag whose argument
95 // is a regular file (or a symlink to one), but doesn't have a
96 // top-level "Clusters" key and therefore isn't a valid cluster
97 // configuration file. If it finds such a flag, it replaces -config
98 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
99 //
100 // This is used by programs that still need to accept "-config" as a
101 // way to specify a per-component config file until their config has
102 // been migrated.
103 //
104 // If any errors are encountered while reading or parsing a config
105 // file, the given args are not munged. We presume the same errors
106 // will be encountered again and reported later on when trying to load
107 // cluster configuration from the same file, regardless of which
108 // struct we end up using.
109 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
110         munged := append([]string(nil), args...)
111         for i := 0; i < len(args); i++ {
112                 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
113                         continue
114                 }
115                 var operand string
116                 if strings.Contains(args[i], "=") {
117                         operand = strings.SplitN(args[i], "=", 2)[1]
118                 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
119                         i++
120                         operand = args[i]
121                 } else {
122                         continue
123                 }
124                 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
125                         continue
126                 }
127                 f, err := os.Open(operand)
128                 if err != nil {
129                         continue
130                 }
131                 defer f.Close()
132                 buf, err := ioutil.ReadAll(f)
133                 if err != nil {
134                         continue
135                 }
136                 var cfg arvados.Config
137                 err = yaml.Unmarshal(buf, &cfg)
138                 if err != nil {
139                         continue
140                 }
141                 if len(cfg.Clusters) == 0 {
142                         lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
143                         if operand == args[i] {
144                                 munged[i-1] = legacyConfigArg
145                         } else {
146                                 munged[i] = legacyConfigArg + "=" + operand
147                         }
148                 }
149         }
150
151         // Disable legacy config loading for components other than the
152         // one that was specified
153         if legacyConfigArg != "-legacy-keepstore-config" {
154                 ldr.KeepstorePath = ""
155         }
156         if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
157                 ldr.CrunchDispatchSlurmPath = ""
158         }
159         if legacyConfigArg != "-legacy-ws-config" {
160                 ldr.WebsocketPath = ""
161         }
162         if legacyConfigArg != "-legacy-keepweb-config" {
163                 ldr.KeepWebPath = ""
164         }
165         if legacyConfigArg != "-legacy-keepproxy-config" {
166                 ldr.KeepproxyPath = ""
167         }
168         if legacyConfigArg != "-legacy-git-httpd-config" {
169                 ldr.GitHttpdPath = ""
170         }
171         if legacyConfigArg != "-legacy-keepbalance-config" {
172                 ldr.KeepBalancePath = ""
173         }
174
175         return munged
176 }
177
178 func (ldr *Loader) loadBytes(path string) (buf []byte, sourceTime, loadTime time.Time, err error) {
179         loadTime = time.Now().UTC()
180         if path == "-" {
181                 buf, err = ioutil.ReadAll(ldr.Stdin)
182                 sourceTime = loadTime
183                 return
184         }
185         f, err := os.Open(path)
186         if err != nil {
187                 return
188         }
189         defer f.Close()
190         fi, err := f.Stat()
191         if err != nil {
192                 return
193         }
194         sourceTime = fi.ModTime().UTC()
195         buf, err = ioutil.ReadAll(f)
196         return
197 }
198
199 func (ldr *Loader) Load() (*arvados.Config, error) {
200         if ldr.configdata == nil {
201                 buf, sourceTime, loadTime, err := ldr.loadBytes(ldr.Path)
202                 if err != nil {
203                         return nil, err
204                 }
205                 ldr.configdata = buf
206                 ldr.sourceTimestamp = sourceTime
207                 ldr.loadTimestamp = loadTime
208         }
209
210         // FIXME: We should reject YAML if the same key is used twice
211         // in a map/object, like {foo: bar, foo: baz}. Maybe we'll get
212         // this fixed free when we upgrade ghodss/yaml to a version
213         // that uses go-yaml v3.
214
215         // Load the config into a dummy map to get the cluster ID
216         // keys, discarding the values; then set up defaults for each
217         // cluster ID; then load the real config on top of the
218         // defaults.
219         var dummy struct {
220                 Clusters map[string]struct{}
221         }
222         err := yaml.Unmarshal(ldr.configdata, &dummy)
223         if err != nil {
224                 return nil, err
225         }
226         if len(dummy.Clusters) == 0 {
227                 return nil, ErrNoClustersDefined
228         }
229
230         // We can't merge deep structs here; instead, we unmarshal the
231         // default & loaded config files into generic maps, merge
232         // those, and then json-encode+decode the result into the
233         // config struct type.
234         var merged map[string]interface{}
235         for id := range dummy.Clusters {
236                 var src map[string]interface{}
237                 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
238                 if err != nil {
239                         return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
240                 }
241                 err = mergo.Merge(&merged, src, mergo.WithOverride)
242                 if err != nil {
243                         return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
244                 }
245         }
246         var src map[string]interface{}
247         err = yaml.Unmarshal(ldr.configdata, &src)
248         if err != nil {
249                 return nil, fmt.Errorf("loading config data: %s", err)
250         }
251         ldr.logExtraKeys(merged, src, "")
252         removeSampleKeys(merged)
253         // We merge the loaded config into the default, overriding any existing keys.
254         // Make sure we do not override a default with a key that has a 'null' value.
255         removeNullKeys(src)
256         err = mergo.Merge(&merged, src, mergo.WithOverride)
257         if err != nil {
258                 return nil, fmt.Errorf("merging config data: %s", err)
259         }
260
261         // map[string]interface{} => json => arvados.Config
262         var cfg arvados.Config
263         var errEnc error
264         pr, pw := io.Pipe()
265         go func() {
266                 errEnc = json.NewEncoder(pw).Encode(merged)
267                 pw.Close()
268         }()
269         err = json.NewDecoder(pr).Decode(&cfg)
270         if errEnc != nil {
271                 err = errEnc
272         }
273         if err != nil {
274                 return nil, fmt.Errorf("transcoding config data: %s", err)
275         }
276
277         var loadFuncs []func(*arvados.Config) error
278         if !ldr.SkipDeprecated {
279                 loadFuncs = append(loadFuncs,
280                         ldr.applyDeprecatedConfig,
281                         ldr.applyDeprecatedVolumeDriverParameters,
282                 )
283         }
284         if !ldr.SkipLegacy {
285                 // legacy file is required when either:
286                 // * a non-default location was specified
287                 // * no primary config was loaded, and this is the
288                 // legacy config file for the current component
289                 loadFuncs = append(loadFuncs,
290                         ldr.loadOldEnvironmentVariables,
291                         ldr.loadOldKeepstoreConfig,
292                         ldr.loadOldKeepWebConfig,
293                         ldr.loadOldCrunchDispatchSlurmConfig,
294                         ldr.loadOldWebsocketConfig,
295                         ldr.loadOldKeepproxyConfig,
296                         ldr.loadOldGitHttpdConfig,
297                         ldr.loadOldKeepBalanceConfig,
298                 )
299         }
300         loadFuncs = append(loadFuncs, ldr.setImplicitStorageClasses)
301         for _, f := range loadFuncs {
302                 err = f(&cfg)
303                 if err != nil {
304                         return nil, err
305                 }
306         }
307
308         // Preprocess/automate some configs
309         for id, cc := range cfg.Clusters {
310                 ldr.autofillPreemptible("Clusters."+id, &cc)
311
312                 if strings.Count(cc.Users.AnonymousUserToken, "/") == 3 {
313                         // V2 token, strip it to just a secret
314                         tmp := strings.Split(cc.Users.AnonymousUserToken, "/")
315                         cc.Users.AnonymousUserToken = tmp[2]
316                 }
317
318                 cfg.Clusters[id] = cc
319         }
320
321         // Check for known mistakes
322         for id, cc := range cfg.Clusters {
323                 for remote := range cc.RemoteClusters {
324                         if remote == "*" || remote == "SAMPLE" {
325                                 continue
326                         }
327                         err = ldr.checkClusterID(fmt.Sprintf("Clusters.%s.RemoteClusters.%s", id, remote), remote, true)
328                         if err != nil {
329                                 return nil, err
330                         }
331                 }
332                 for _, err = range []error{
333                         ldr.checkClusterID(fmt.Sprintf("Clusters.%s", id), id, false),
334                         ldr.checkClusterID(fmt.Sprintf("Clusters.%s.Login.LoginCluster", id), cc.Login.LoginCluster, true),
335                         ldr.checkToken(fmt.Sprintf("Clusters.%s.ManagementToken", id), cc.ManagementToken, true, false),
336                         ldr.checkToken(fmt.Sprintf("Clusters.%s.SystemRootToken", id), cc.SystemRootToken, true, false),
337                         ldr.checkToken(fmt.Sprintf("Clusters.%s.Users.AnonymousUserToken", id), cc.Users.AnonymousUserToken, false, true),
338                         ldr.checkToken(fmt.Sprintf("Clusters.%s.Collections.BlobSigningKey", id), cc.Collections.BlobSigningKey, true, false),
339                         checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection),
340                         ldr.checkEnum("Containers.LocalKeepLogsToContainerLog", cc.Containers.LocalKeepLogsToContainerLog, "none", "all", "errors"),
341                         ldr.checkEmptyKeepstores(cc),
342                         ldr.checkUnlistedKeepstores(cc),
343                         ldr.checkLocalKeepBlobBuffers(cc),
344                         ldr.checkStorageClasses(cc),
345                         ldr.checkCUDAVersions(cc),
346                         // TODO: check non-empty Rendezvous on
347                         // services other than Keepstore
348                 } {
349                         if err != nil {
350                                 return nil, err
351                         }
352                 }
353         }
354         cfg.SourceTimestamp = ldr.sourceTimestamp
355         cfg.SourceSHA256 = fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
356         return &cfg, nil
357 }
358
359 var acceptableClusterIDRe = regexp.MustCompile(`^[a-z0-9]{5}$`)
360
361 func (ldr *Loader) checkClusterID(label, clusterID string, emptyStringOk bool) error {
362         if emptyStringOk && clusterID == "" {
363                 return nil
364         } else if !acceptableClusterIDRe.MatchString(clusterID) {
365                 return fmt.Errorf("%s: cluster ID should be 5 alphanumeric characters", label)
366         }
367         return nil
368 }
369
370 var acceptableTokenRe = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
371 var acceptableTokenLength = 32
372
373 func (ldr *Loader) checkToken(label, token string, mandatory bool, acceptV2 bool) error {
374         if len(token) == 0 {
375                 if !mandatory {
376                         // when a token is not mandatory, the acceptable length and content is only checked if its length is non-zero
377                         return nil
378                 } else {
379                         if ldr.Logger != nil {
380                                 ldr.Logger.Warnf("%s: secret token is not set (use %d+ random characters from a-z, A-Z, 0-9)", label, acceptableTokenLength)
381                         }
382                 }
383         } else if !acceptableTokenRe.MatchString(token) {
384                 if !acceptV2 {
385                         return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
386                 }
387                 // Test for a proper V2 token
388                 tmp := strings.SplitN(token, "/", 3)
389                 if len(tmp) != 3 {
390                         return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
391                 }
392                 if !strings.HasPrefix(token, "v2/") {
393                         return fmt.Errorf("%s: unacceptable characters in token (only a-z, A-Z, 0-9 are acceptable)", label)
394                 }
395                 if !acceptableTokenRe.MatchString(tmp[2]) {
396                         return fmt.Errorf("%s: unacceptable characters in V2 token secret (only a-z, A-Z, 0-9 are acceptable)", label)
397                 }
398                 if len(tmp[2]) < acceptableTokenLength {
399                         ldr.Logger.Warnf("%s: secret is too short (should be at least %d characters)", label, acceptableTokenLength)
400                 }
401         } else if len(token) < acceptableTokenLength {
402                 if ldr.Logger != nil {
403                         ldr.Logger.Warnf("%s: token is too short (should be at least %d characters)", label, acceptableTokenLength)
404                 }
405         }
406         return nil
407 }
408
409 func (ldr *Loader) checkEnum(label, value string, accepted ...string) error {
410         for _, s := range accepted {
411                 if s == value {
412                         return nil
413                 }
414         }
415         return fmt.Errorf("%s: unacceptable value %q: must be one of %q", label, value, accepted)
416 }
417
418 func (ldr *Loader) setImplicitStorageClasses(cfg *arvados.Config) error {
419 cluster:
420         for id, cc := range cfg.Clusters {
421                 if len(cc.StorageClasses) > 0 {
422                         continue cluster
423                 }
424                 for _, vol := range cc.Volumes {
425                         if len(vol.StorageClasses) > 0 {
426                                 continue cluster
427                         }
428                 }
429                 // No explicit StorageClasses config info at all; fill
430                 // in implicit defaults.
431                 for id, vol := range cc.Volumes {
432                         vol.StorageClasses = map[string]bool{"default": true}
433                         cc.Volumes[id] = vol
434                 }
435                 cc.StorageClasses = map[string]arvados.StorageClassConfig{"default": {Default: true}}
436                 cfg.Clusters[id] = cc
437         }
438         return nil
439 }
440
441 func (ldr *Loader) checkLocalKeepBlobBuffers(cc arvados.Cluster) error {
442         kbb := cc.Containers.LocalKeepBlobBuffersPerVCPU
443         if kbb == 0 {
444                 return nil
445         }
446         for uuid, vol := range cc.Volumes {
447                 if len(vol.AccessViaHosts) > 0 {
448                         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)
449                         return nil
450                 }
451                 if !vol.ReadOnly && vol.Replication < cc.Collections.DefaultReplication {
452                         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)
453                         return nil
454                 }
455         }
456         return nil
457 }
458
459 func (ldr *Loader) checkStorageClasses(cc arvados.Cluster) error {
460         classOnVolume := map[string]bool{}
461         for volid, vol := range cc.Volumes {
462                 if len(vol.StorageClasses) == 0 {
463                         return fmt.Errorf("%s: volume has no StorageClasses listed", volid)
464                 }
465                 for classid := range vol.StorageClasses {
466                         if _, ok := cc.StorageClasses[classid]; !ok {
467                                 return fmt.Errorf("%s: volume refers to storage class %q that is not defined in StorageClasses", volid, classid)
468                         }
469                         classOnVolume[classid] = true
470                 }
471         }
472         haveDefault := false
473         for classid, sc := range cc.StorageClasses {
474                 if !classOnVolume[classid] && len(cc.Volumes) > 0 {
475                         ldr.Logger.Warnf("there are no volumes providing storage class %q", classid)
476                 }
477                 if sc.Default {
478                         haveDefault = true
479                 }
480         }
481         if !haveDefault {
482                 return fmt.Errorf("there is no default storage class (at least one entry in StorageClasses must have Default: true)")
483         }
484         return nil
485 }
486
487 func (ldr *Loader) checkCUDAVersions(cc arvados.Cluster) error {
488         for _, it := range cc.InstanceTypes {
489                 if it.CUDA.DeviceCount == 0 {
490                         continue
491                 }
492
493                 _, err := strconv.ParseFloat(it.CUDA.DriverVersion, 64)
494                 if err != nil {
495                         return fmt.Errorf("InstanceType %q has invalid CUDA.DriverVersion %q, expected format X.Y (%v)", it.Name, it.CUDA.DriverVersion, err)
496                 }
497                 _, err = strconv.ParseFloat(it.CUDA.HardwareCapability, 64)
498                 if err != nil {
499                         return fmt.Errorf("InstanceType %q has invalid CUDA.HardwareCapability %q, expected format X.Y (%v)", it.Name, it.CUDA.HardwareCapability, err)
500                 }
501         }
502         return nil
503 }
504
505 func checkKeyConflict(label string, m map[string]string) error {
506         saw := map[string]bool{}
507         for k := range m {
508                 k = strings.ToLower(k)
509                 if saw[k] {
510                         return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
511                 }
512                 saw[k] = true
513         }
514         return nil
515 }
516
517 func removeNullKeys(m map[string]interface{}) {
518         for k, v := range m {
519                 if v == nil {
520                         delete(m, k)
521                 }
522                 if v, _ := v.(map[string]interface{}); v != nil {
523                         removeNullKeys(v)
524                 }
525         }
526 }
527
528 func removeSampleKeys(m map[string]interface{}) {
529         delete(m, "SAMPLE")
530         for _, v := range m {
531                 if v, _ := v.(map[string]interface{}); v != nil {
532                         removeSampleKeys(v)
533                 }
534         }
535 }
536
537 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
538         if ldr.Logger == nil {
539                 return
540         }
541         for k, vsupp := range supplied {
542                 if k == "SAMPLE" {
543                         // entry will be dropped in removeSampleKeys anyway
544                         continue
545                 }
546                 vexp, ok := expected[k]
547                 if expected["SAMPLE"] != nil {
548                         // use the SAMPLE entry's keys as the
549                         // "expected" map when checking vsupp
550                         // recursively.
551                         vexp = expected["SAMPLE"]
552                 } else if !ok {
553                         // check for a case-insensitive match
554                         hint := ""
555                         for ek := range expected {
556                                 if strings.EqualFold(k, ek) {
557                                         hint = " (perhaps you meant " + ek + "?)"
558                                         // If we don't delete this, it
559                                         // will end up getting merged,
560                                         // unpredictably
561                                         // merging/overriding the
562                                         // default.
563                                         delete(supplied, k)
564                                         break
565                                 }
566                         }
567                         ldr.Logger.Warnf("deprecated or unknown config entry: %s%s%s", prefix, k, hint)
568                         continue
569                 }
570                 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
571                         // if vsupp is a map but vexp isn't map, this
572                         // will be caught elsewhere; see TestBadType.
573                         continue
574                 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
575                         ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
576                 } else {
577                         ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
578                 }
579         }
580 }
581
582 func (ldr *Loader) autofillPreemptible(label string, cc *arvados.Cluster) {
583         if factor := cc.Containers.PreemptiblePriceFactor; factor > 0 {
584                 for name, it := range cc.InstanceTypes {
585                         if !it.Preemptible {
586                                 it.Preemptible = true
587                                 it.Price = it.Price * factor
588                                 it.Name = name + ".preemptible"
589                                 if it2, exists := cc.InstanceTypes[it.Name]; exists && it2 != it {
590                                         ldr.Logger.Warnf("%s.InstanceTypes[%s]: already exists, so not automatically adding a preemptible variant of %s", label, it.Name, name)
591                                         continue
592                                 }
593                                 cc.InstanceTypes[it.Name] = it
594                         }
595                 }
596         }
597
598 }
599
600 // RegisterMetrics registers metrics showing the timestamp and content
601 // hash of the currently loaded config.
602 //
603 // Must not be called more than once for a given registry. Must not be
604 // called before Load(). Metrics are not updated by subsequent calls
605 // to Load().
606 func (ldr *Loader) RegisterMetrics(reg *prometheus.Registry) {
607         hash := fmt.Sprintf("%x", sha256.Sum256(ldr.configdata))
608         vec := prometheus.NewGaugeVec(prometheus.GaugeOpts{
609                 Namespace: "arvados",
610                 Subsystem: "config",
611                 Name:      "source_timestamp_seconds",
612                 Help:      "Timestamp of config file when it was loaded.",
613         }, []string{"sha256"})
614         vec.WithLabelValues(hash).Set(float64(ldr.sourceTimestamp.UnixNano()) / 1e9)
615         reg.MustRegister(vec)
616
617         vec = prometheus.NewGaugeVec(prometheus.GaugeOpts{
618                 Namespace: "arvados",
619                 Subsystem: "config",
620                 Name:      "load_timestamp_seconds",
621                 Help:      "Time when config file was loaded.",
622         }, []string{"sha256"})
623         vec.WithLabelValues(hash).Set(float64(ldr.loadTimestamp.UnixNano()) / 1e9)
624         reg.MustRegister(vec)
625 }