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