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