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