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