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