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