14715: Adds keepproxy to cluster config loading
[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         CrunchDispatchSlurmPath string
35         WebsocketPath           string
36         KeepproxyPath           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.CrunchDispatchSlurmPath, "legacy-crunch-dispatch-slurm-config", defaultCrunchDispatchSlurmConfigPath, "Legacy crunch-dispatch-slurm configuration `file`")
65         flagset.StringVar(&ldr.WebsocketPath, "legacy-ws-config", defaultWebsocketConfigPath, "Legacy arvados-ws configuration `file`")
66         flagset.StringVar(&ldr.KeepproxyPath, "legacy-keepproxy-config", defaultKeepproxyConfigPath, "Legacy keepproxy 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         if legacyConfigArg != "-legacy-keepproxy-config" {
139                 ldr.WebsocketPath = ""
140         }
141
142         return munged
143 }
144
145 func (ldr *Loader) loadBytes(path string) ([]byte, error) {
146         if path == "-" {
147                 return ioutil.ReadAll(ldr.Stdin)
148         }
149         f, err := os.Open(path)
150         if err != nil {
151                 return nil, err
152         }
153         defer f.Close()
154         return ioutil.ReadAll(f)
155 }
156
157 func (ldr *Loader) Load() (*arvados.Config, error) {
158         if ldr.configdata == nil {
159                 buf, err := ldr.loadBytes(ldr.Path)
160                 if err != nil {
161                         return nil, err
162                 }
163                 ldr.configdata = buf
164         }
165
166         // Load the config into a dummy map to get the cluster ID
167         // keys, discarding the values; then set up defaults for each
168         // cluster ID; then load the real config on top of the
169         // defaults.
170         var dummy struct {
171                 Clusters map[string]struct{}
172         }
173         err := yaml.Unmarshal(ldr.configdata, &dummy)
174         if err != nil {
175                 return nil, err
176         }
177         if len(dummy.Clusters) == 0 {
178                 return nil, ErrNoClustersDefined
179         }
180
181         // We can't merge deep structs here; instead, we unmarshal the
182         // default & loaded config files into generic maps, merge
183         // those, and then json-encode+decode the result into the
184         // config struct type.
185         var merged map[string]interface{}
186         for id := range dummy.Clusters {
187                 var src map[string]interface{}
188                 err = yaml.Unmarshal(bytes.Replace(DefaultYAML, []byte(" xxxxx:"), []byte(" "+id+":"), -1), &src)
189                 if err != nil {
190                         return nil, fmt.Errorf("loading defaults for %s: %s", id, err)
191                 }
192                 err = mergo.Merge(&merged, src, mergo.WithOverride)
193                 if err != nil {
194                         return nil, fmt.Errorf("merging defaults for %s: %s", id, err)
195                 }
196         }
197         var src map[string]interface{}
198         err = yaml.Unmarshal(ldr.configdata, &src)
199         if err != nil {
200                 return nil, fmt.Errorf("loading config data: %s", err)
201         }
202         ldr.logExtraKeys(merged, src, "")
203         removeSampleKeys(merged)
204         err = mergo.Merge(&merged, src, mergo.WithOverride)
205         if err != nil {
206                 return nil, fmt.Errorf("merging config data: %s", err)
207         }
208
209         // map[string]interface{} => json => arvados.Config
210         var cfg arvados.Config
211         var errEnc error
212         pr, pw := io.Pipe()
213         go func() {
214                 errEnc = json.NewEncoder(pw).Encode(merged)
215                 pw.Close()
216         }()
217         err = json.NewDecoder(pr).Decode(&cfg)
218         if errEnc != nil {
219                 err = errEnc
220         }
221         if err != nil {
222                 return nil, fmt.Errorf("transcoding config data: %s", err)
223         }
224
225         if !ldr.SkipDeprecated {
226                 err = ldr.applyDeprecatedConfig(&cfg)
227                 if err != nil {
228                         return nil, err
229                 }
230         }
231         if !ldr.SkipLegacy {
232                 // legacy file is required when either:
233                 // * a non-default location was specified
234                 // * no primary config was loaded, and this is the
235                 // legacy config file for the current component
236                 for _, err := range []error{
237                         ldr.loadOldKeepstoreConfig(&cfg),
238                         ldr.loadOldCrunchDispatchSlurmConfig(&cfg),
239                         ldr.loadOldWebsocketConfig(&cfg),
240                         ldr.loadOldKeepproxyConfig(&cfg),
241                 } {
242                         if err != nil {
243                                 return nil, err
244                         }
245                 }
246         }
247
248         // Check for known mistakes
249         for id, cc := range cfg.Clusters {
250                 err = checkKeyConflict(fmt.Sprintf("Clusters.%s.PostgreSQL.Connection", id), cc.PostgreSQL.Connection)
251                 if err != nil {
252                         return nil, err
253                 }
254         }
255         return &cfg, nil
256 }
257
258 func checkKeyConflict(label string, m map[string]string) error {
259         saw := map[string]bool{}
260         for k := range m {
261                 k = strings.ToLower(k)
262                 if saw[k] {
263                         return fmt.Errorf("%s: multiple entries for %q (fix by using same capitalization as default/example file)", label, k)
264                 }
265                 saw[k] = true
266         }
267         return nil
268 }
269
270 func removeSampleKeys(m map[string]interface{}) {
271         delete(m, "SAMPLE")
272         for _, v := range m {
273                 if v, _ := v.(map[string]interface{}); v != nil {
274                         removeSampleKeys(v)
275                 }
276         }
277 }
278
279 func (ldr *Loader) logExtraKeys(expected, supplied map[string]interface{}, prefix string) {
280         if ldr.Logger == nil {
281                 return
282         }
283         allowed := map[string]interface{}{}
284         for k, v := range expected {
285                 allowed[strings.ToLower(k)] = v
286         }
287         for k, vsupp := range supplied {
288                 if k == "SAMPLE" {
289                         // entry will be dropped in removeSampleKeys anyway
290                         continue
291                 }
292                 vexp, ok := allowed[strings.ToLower(k)]
293                 if expected["SAMPLE"] != nil {
294                         vexp = expected["SAMPLE"]
295                 } else if !ok {
296                         ldr.Logger.Warnf("deprecated or unknown config entry: %s%s", prefix, k)
297                         continue
298                 }
299                 if vsupp, ok := vsupp.(map[string]interface{}); !ok {
300                         // if vsupp is a map but vexp isn't map, this
301                         // will be caught elsewhere; see TestBadType.
302                         continue
303                 } else if vexp, ok := vexp.(map[string]interface{}); !ok {
304                         ldr.Logger.Warnf("unexpected object in config entry: %s%s", prefix, k)
305                 } else {
306                         ldr.logExtraKeys(vexp, vsupp, prefix+k+".")
307                 }
308         }
309 }