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