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