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