Merge branch '15467-legacy-config' refs #15467
[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         "strings"
17
18         "git.curoverse.com/arvados.git/sdk/go/arvados"
19         "github.com/ghodss/yaml"
20         "github.com/imdario/mergo"
21         "github.com/sirupsen/logrus"
22 )
23
24 var ErrNoClustersDefined = errors.New("config does not define any clusters")
25
26 type Loader struct {
27         Stdin          io.Reader
28         Logger         logrus.FieldLogger
29         SkipDeprecated bool // Don't load deprecated config keys
30         SkipLegacy     bool // Don't load legacy config files
31
32         Path                    string
33         KeepstorePath           string
34         CrunchDispatchSlurmPath string
35         WebsocketPath           string
36
37         configdata []byte
38 }
39
40 // NewLoader returns a new Loader with Stdin and Logger set to the
41 // given values, and all config paths set to their default values.
42 func NewLoader(stdin io.Reader, logger logrus.FieldLogger) *Loader {
43         ldr := &Loader{Stdin: stdin, Logger: logger}
44         // Calling SetupFlags on a throwaway FlagSet has the side
45         // effect of assigning default values to the configurable
46         // fields.
47         ldr.SetupFlags(flag.NewFlagSet("", flag.ContinueOnError))
48         return ldr
49 }
50
51 // SetupFlags configures a flagset so arguments like -config X can be
52 // used to change the loader's Path fields.
53 //
54 //      ldr := NewLoader(os.Stdin, logrus.New())
55 //      flagset := flag.NewFlagSet("", flag.ContinueOnError)
56 //      ldr.SetupFlags(flagset)
57 //      // ldr.Path == "/etc/arvados/config.yml"
58 //      flagset.Parse([]string{"-config", "/tmp/c.yaml"})
59 //      // ldr.Path == "/tmp/c.yaml"
60 func (ldr *Loader) SetupFlags(flagset *flag.FlagSet) {
61         flagset.StringVar(&ldr.Path, "config", arvados.DefaultConfigFile, "Site configuration `file` (default may be overridden by setting an ARVADOS_CONFIG environment variable)")
62         flagset.StringVar(&ldr.KeepstorePath, "legacy-keepstore-config", defaultKeepstoreConfigPath, "Legacy keepstore configuration `file`")
63         flagset.StringVar(&ldr.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
64         flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
65         flagset.BoolVar(&ldr.SkipLegacy, "skip-legacy", false, "Don't load legacy config files")
66 }
67
68 // MungeLegacyConfigArgs checks args for a -config flag whose argument
69 // is a regular file (or a symlink to one), but doesn't have a
70 // top-level "Clusters" key and therefore isn't a valid cluster
71 // configuration file. If it finds such a flag, it replaces -config
72 // with legacyConfigArg (e.g., "-legacy-keepstore-config").
73 //
74 // This is used by programs that still need to accept "-config" as a
75 // way to specify a per-component config file until their config has
76 // been migrated.
77 //
78 // If any errors are encountered while reading or parsing a config
79 // file, the given args are not munged. We presume the same errors
80 // will be encountered again and reported later on when trying to load
81 // cluster configuration from the same file, regardless of which
82 // struct we end up using.
83 func (ldr *Loader) MungeLegacyConfigArgs(lgr logrus.FieldLogger, args []string, legacyConfigArg string) []string {
84         munged := append([]string(nil), args...)
85         for i := 0; i < len(args); i++ {
86                 if !strings.HasPrefix(args[i], "-") || strings.SplitN(strings.TrimPrefix(args[i], "-"), "=", 2)[0] != "config" {
87                         continue
88                 }
89                 var operand string
90                 if strings.Contains(args[i], "=") {
91                         operand = strings.SplitN(args[i], "=", 2)[1]
92                 } else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
93                         i++
94                         operand = args[i]
95                 } else {
96                         continue
97                 }
98                 if fi, err := os.Stat(operand); err != nil || !fi.Mode().IsRegular() {
99                         continue
100                 }
101                 f, err := os.Open(operand)
102                 if err != nil {
103                         continue
104                 }
105                 defer f.Close()
106                 buf, err := ioutil.ReadAll(f)
107                 if err != nil {
108                         continue
109                 }
110                 var cfg arvados.Config
111                 err = yaml.Unmarshal(buf, &cfg)
112                 if err != nil {
113                         continue
114                 }
115                 if len(cfg.Clusters) == 0 {
116                         lgr.Warnf("%s is not a cluster config file -- interpreting %s as %s (please migrate your config!)", operand, "-config", legacyConfigArg)
117                         if operand == args[i] {
118                                 munged[i-1] = legacyConfigArg
119                         } else {
120                                 munged[i] = legacyConfigArg + "=" + operand
121                         }
122                 }
123         }
124
125         // Disable legacy config loading for components other than the
126         // one that was specified
127         if legacyConfigArg != "-legacy-keepstore-config" {
128                 ldr.KeepstorePath = ""
129         }
130         if legacyConfigArg != "-legacy-crunch-dispatch-slurm-config" {
131                 ldr.CrunchDispatchSlurmPath = ""
132         }
133         if legacyConfigArg != "-legacy-ws-config" {
134                 ldr.WebsocketPath = ""
135         }
136
137         return munged
138 }
139
140 func (ldr *Loader) loadBytes(path string) ([]byte, error) {
141         if path == "-" {
142                 return ioutil.ReadAll(ldr.Stdin)
143         }
144         f, err := os.Open(path)
145         if err != nil {
146                 return nil, err
147         }
148         defer f.Close()
149         return ioutil.ReadAll(f)
150 }
151
152 func (ldr *Loader) Load() (*arvados.Config, error) {
153         if ldr.configdata == nil {
154                 buf, err := ldr.loadBytes(ldr.Path)
155                 if err != nil {
156                         return nil, err
157                 }
158                 ldr.configdata = buf
159         }
160
161         // Load the config into a dummy map to get the cluster ID
162         // keys, discarding the values; then set up defaults for each
163         // cluster ID; then load the real config on top of the
164         // defaults.
165         var dummy struct {
166                 Clusters map[string]struct{}
167         }
168         err := yaml.Unmarshal(ldr.configdata, &dummy)
169         if err != nil {
170                 return nil, err
171         }
172         if len(dummy.Clusters) == 0 {
173                 return nil, ErrNoClustersDefined
174         }
175
176         // We can't merge deep structs here; instead, we unmarshal the
177         // default & loaded config files into generic maps, merge
178         // those, and then json-encode+decode the result into the
179         // config struct type.
180         var merged map[string]interface{}
181         for id := range dummy.Clusters {
182                 var src map[string]interface{}
183                 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
184                 if err != nil {
185                         return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
186                 }
187                 err = mergo.Merge(&merged, src, mergo.WithOverride)
188                 if err != nil {
189                         return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
190                 }
191         }
192         var src map[string]interface{}
193         err = yaml.Unmarshal(ldr.configdata, &src)
194         if err != nil {
195                 return nil, fmt.Errorf("loading config data: %s", err)
196         }
197         ldr.logExtraKeys(merged, src, "")
198         removeSampleKeys(merged)
199         err = mergo.Merge(&merged, src, mergo.WithOverride)
200         if err != nil {
201                 return nil, fmt.Errorf("merging config data: %s", err)
202         }
203
204         // map[string]interface{} => json => arvados.Config
205         var cfg arvados.Config
206         var errEnc error
207         pr, pw := io.Pipe()
208         go func() {
209                 errEnc = json.NewEncoder(pw).Encode(merged)
210                 pw.Close()
211         }()
212         err = json.NewDecoder(pr).Decode(&cfg)
213         if errEnc != nil {
214                 err = errEnc
215         }
216         if err != nil {
217                 return nil, fmt.Errorf("transcoding config data: %s", err)
218         }
219
220         if !ldr.SkipDeprecated {
221                 err = ldr.applyDeprecatedConfig(&cfg)
222                 if err != nil {
223                         return nil, err
224                 }
225         }
226         if !ldr.SkipLegacy {
227                 // legacy file is required when either:
228                 // * a non-default location was specified
229                 // * no primary config was loaded, and this is the
230                 // legacy config file for the current component
231                 for _, err := range []error{
232                         ldr.loadOldKeepstoreConfig(&cfg),
233                         ldr.loadOldCrunchDispatchSlurmConfig(&cfg),
234                         ldr.loadOldWebsocketConfig(&cfg),
235                 } {
236                         if err != nil {
237                                 return nil, err
238                         }
239                 }
240         }
241
242         // Check for known mistakes
243         for id, cc := range cfg.Clusters {
244                 err = checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection)
245                 if err != nil {
246                         return nil, err
247                 }
248         }
249         return &cfg, nil
250 }
251
252 func checkKeyConflict(label string, m map[string]string) error {
253         saw := map[string]bool{}
254         for k := range m {
255                 k = strings.ToLower(k)
256                 if saw[k] {
257                         return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
258                 }
259                 saw[k] = true
260         }
261         return nil
262 }
263
264 func removeSampleKeys(m map[string]interface{}) {
265         delete(m, "SAMPLE")
266         for _, v := range m {
267                 if v, _ := v.(map[string]interface{}); v != nil {
268                         removeSampleKeys(v)
269                 }
270         }
271 }
272
273 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
274         if ldr.Logger == nil {
275                 return
276         }
277         allowed := map[string]interface{}{}
278         for k, v := range expected {
279                 allowed[strings.ToLower(k)] = v
280         }
281         for k, vsupp := range supplied {
282                 if k == "SAMPLE" {
283                         // entry will be dropped in removeSampleKeys anyway
284                         continue
285                 }
286                 vexp, ok := allowed[strings.ToLower(k)]
287                 if expected["SAMPLE"] != nil {
288                         vexp = expected["SAMPLE"]
289                 } else if !ok {
290                         ldr.Logger.Warnf("deprecated or unknown config entry: %s%s", prefix, k)
291                         continue
292                 }
293                 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
294                         // if vsupp is a map but vexp isn't map, this
295                         // will be caught elsewhere; see TestBadType.
296                         continue
297                 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
298                         ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
299                 } else {
300                         ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
301                 }
302         }
303 }