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