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