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