Merge branch 'master' into 15319-api-useful-stacktraces
[arvados.git] / lib / config / load_test.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         "fmt"
10         "io"
11         "io/ioutil"
12         "os"
13         "os/exec"
14         "reflect"
15         "strings"
16         "testing"
17
18         "git.curoverse.com/arvados.git/sdk/go/arvados"
19         "git.curoverse.com/arvados.git/sdk/go/ctxlog"
20         "github.com/ghodss/yaml"
21         "github.com/sirupsen/logrus"
22         check "gopkg.in/check.v1"
23 )
24
25 // Gocheck boilerplate
26 func Test(t *testing.T) {
27         check.TestingT(t)
28 }
29
30 var _ = check.Suite(&LoadSuite{})
31
32 // Return a new Loader that reads cluster config from configdata
33 // (instead of the usual default /etc/arvados/config.yml), and logs to
34 // logdst or (if that's nil) c.Log.
35 func testLoader(c *check.C, configdata string, logdst io.Writer) *Loader {
36         logger := ctxlog.TestLogger(c)
37         if logdst != nil {
38                 lgr := logrus.New()
39                 lgr.Out = logdst
40                 logger = lgr
41         }
42         ldr := NewLoader(bytes.NewBufferString(configdata), logger)
43         ldr.Path = "-"
44         return ldr
45 }
46
47 type LoadSuite struct{}
48
49 func (s *LoadSuite) TestEmpty(c *check.C) {
50         cfg, err := testLoader(c, "", nil).Load()
51         c.Check(cfg, check.IsNil)
52         c.Assert(err, check.ErrorMatches, `config does not define any clusters`)
53 }
54
55 func (s *LoadSuite) TestNoConfigs(c *check.C) {
56         cfg, err := testLoader(c, `Clusters: {"z1111": {}}`, nil).Load()
57         c.Assert(err, check.IsNil)
58         c.Assert(cfg.Clusters, check.HasLen, 1)
59         cc, err := cfg.GetCluster("z1111")
60         c.Assert(err, check.IsNil)
61         c.Check(cc.ClusterID, check.Equals, "z1111")
62         c.Check(cc.API.MaxRequestAmplification, check.Equals, 4)
63         c.Check(cc.API.MaxItemsPerResponse, check.Equals, 1000)
64 }
65
66 func (s *LoadSuite) TestMungeLegacyConfigArgs(c *check.C) {
67         f, err := ioutil.TempFile("", "")
68         c.Check(err, check.IsNil)
69         defer os.Remove(f.Name())
70         io.WriteString(f, "Debug: true\n")
71         oldfile := f.Name()
72
73         f, err = ioutil.TempFile("", "")
74         c.Check(err, check.IsNil)
75         defer os.Remove(f.Name())
76         io.WriteString(f, "Clusters: {aaaaa: {}}\n")
77         newfile := f.Name()
78
79         for _, trial := range []struct {
80                 argsIn  []string
81                 argsOut []string
82         }{
83                 {
84                         []string{"-config", oldfile},
85                         []string{"-old-config", oldfile},
86                 },
87                 {
88                         []string{"-config=" + oldfile},
89                         []string{"-old-config=" + oldfile},
90                 },
91                 {
92                         []string{"-config", newfile},
93                         []string{"-config", newfile},
94                 },
95                 {
96                         []string{"-config=" + newfile},
97                         []string{"-config=" + newfile},
98                 },
99                 {
100                         []string{"-foo", oldfile},
101                         []string{"-foo", oldfile},
102                 },
103                 {
104                         []string{"-foo=" + oldfile},
105                         []string{"-foo=" + oldfile},
106                 },
107                 {
108                         []string{"-foo", "-config=" + oldfile},
109                         []string{"-foo", "-old-config=" + oldfile},
110                 },
111                 {
112                         []string{"-foo", "bar", "-config=" + oldfile},
113                         []string{"-foo", "bar", "-old-config=" + oldfile},
114                 },
115                 {
116                         []string{"-foo=bar", "baz", "-config=" + oldfile},
117                         []string{"-foo=bar", "baz", "-old-config=" + oldfile},
118                 },
119                 {
120                         []string{"-config=/dev/null"},
121                         []string{"-config=/dev/null"},
122                 },
123                 {
124                         []string{"-config=-"},
125                         []string{"-config=-"},
126                 },
127                 {
128                         []string{"-config="},
129                         []string{"-config="},
130                 },
131                 {
132                         []string{"-foo=bar", "baz", "-config"},
133                         []string{"-foo=bar", "baz", "-config"},
134                 },
135                 {
136                         []string{},
137                         nil,
138                 },
139         } {
140                 var logbuf bytes.Buffer
141                 logger := logrus.New()
142                 logger.Out = &logbuf
143
144                 var ldr Loader
145                 args := ldr.MungeLegacyConfigArgs(logger, trial.argsIn, "-old-config")
146                 c.Check(args, check.DeepEquals, trial.argsOut)
147                 if fmt.Sprintf("%v", trial.argsIn) != fmt.Sprintf("%v", trial.argsOut) {
148                         c.Check(logbuf.String(), check.Matches, `.*`+oldfile+` is not a cluster config file -- interpreting -config as -old-config.*\n`)
149                 }
150         }
151 }
152
153 func (s *LoadSuite) TestSampleKeys(c *check.C) {
154         for _, yaml := range []string{
155                 `{"Clusters":{"z1111":{}}}`,
156                 `{"Clusters":{"z1111":{"InstanceTypes":{"Foo":{"RAM": "12345M"}}}}}`,
157         } {
158                 cfg, err := testLoader(c, yaml, nil).Load()
159                 c.Assert(err, check.IsNil)
160                 cc, err := cfg.GetCluster("z1111")
161                 _, hasSample := cc.InstanceTypes["SAMPLE"]
162                 c.Check(hasSample, check.Equals, false)
163                 if strings.Contains(yaml, "Foo") {
164                         c.Check(cc.InstanceTypes["Foo"].RAM, check.Equals, arvados.ByteSize(12345000000))
165                         c.Check(cc.InstanceTypes["Foo"].Price, check.Equals, 0.0)
166                 }
167         }
168 }
169
170 func (s *LoadSuite) TestMultipleClusters(c *check.C) {
171         cfg, err := testLoader(c, `{"Clusters":{"z1111":{},"z2222":{}}}`, nil).Load()
172         c.Assert(err, check.IsNil)
173         c1, err := cfg.GetCluster("z1111")
174         c.Assert(err, check.IsNil)
175         c.Check(c1.ClusterID, check.Equals, "z1111")
176         c2, err := cfg.GetCluster("z2222")
177         c.Assert(err, check.IsNil)
178         c.Check(c2.ClusterID, check.Equals, "z2222")
179 }
180
181 func (s *LoadSuite) TestDeprecatedOrUnknownWarning(c *check.C) {
182         var logbuf bytes.Buffer
183         _, err := testLoader(c, `
184 Clusters:
185   zzzzz:
186     postgresql: {}
187     BadKey: {}
188     Containers: {}
189     RemoteClusters:
190       z2222:
191         Host: z2222.arvadosapi.com
192         Proxy: true
193         BadKey: badValue
194 `, &logbuf).Load()
195         c.Assert(err, check.IsNil)
196         logs := strings.Split(strings.TrimSuffix(logbuf.String(), "\n"), "\n")
197         for _, log := range logs {
198                 c.Check(log, check.Matches, `.*deprecated or unknown config entry:.*BadKey.*`)
199         }
200         c.Check(logs, check.HasLen, 2)
201 }
202
203 func (s *LoadSuite) checkSAMPLEKeys(c *check.C, path string, x interface{}) {
204         v := reflect.Indirect(reflect.ValueOf(x))
205         switch v.Kind() {
206         case reflect.Map:
207                 var stringKeys, sampleKey bool
208                 iter := v.MapRange()
209                 for iter.Next() {
210                         k := iter.Key()
211                         if k.Kind() == reflect.String {
212                                 stringKeys = true
213                                 if k.String() == "SAMPLE" || k.String() == "xxxxx" {
214                                         sampleKey = true
215                                         s.checkSAMPLEKeys(c, path+"."+k.String(), iter.Value().Interface())
216                                 }
217                         }
218                 }
219                 if stringKeys && !sampleKey {
220                         c.Errorf("%s is a map with string keys (type %T) but config.default.yml has no SAMPLE key", path, x)
221                 }
222                 return
223         case reflect.Struct:
224                 for i := 0; i < v.NumField(); i++ {
225                         val := v.Field(i)
226                         if val.CanInterface() {
227                                 s.checkSAMPLEKeys(c, path+"."+v.Type().Field(i).Name, val.Interface())
228                         }
229                 }
230         }
231 }
232
233 func (s *LoadSuite) TestDefaultConfigHasAllSAMPLEKeys(c *check.C) {
234         cfg, err := Load(bytes.NewBuffer(DefaultYAML), ctxlog.TestLogger(c))
235         c.Assert(err, check.IsNil)
236         s.checkSAMPLEKeys(c, "", cfg)
237 }
238
239 func (s *LoadSuite) TestNoUnrecognizedKeysInDefaultConfig(c *check.C) {
240         var logbuf bytes.Buffer
241         var supplied map[string]interface{}
242         yaml.Unmarshal(DefaultYAML, &supplied)
243
244         loader := testLoader(c, string(DefaultYAML), &logbuf)
245         cfg, err := loader.Load()
246         c.Assert(err, check.IsNil)
247         var loaded map[string]interface{}
248         buf, err := yaml.Marshal(cfg)
249         c.Assert(err, check.IsNil)
250         err = yaml.Unmarshal(buf, &loaded)
251         c.Assert(err, check.IsNil)
252
253         loader.logExtraKeys(loaded, supplied, "")
254         c.Check(logbuf.String(), check.Equals, "")
255 }
256
257 func (s *LoadSuite) TestNoWarningsForDumpedConfig(c *check.C) {
258         var logbuf bytes.Buffer
259         logger := logrus.New()
260         logger.Out = &logbuf
261         cfg, err := testLoader(c, `{"Clusters":{"zzzzz":{}}}`, &logbuf).Load()
262         c.Assert(err, check.IsNil)
263         yaml, err := yaml.Marshal(cfg)
264         c.Assert(err, check.IsNil)
265         cfgDumped, err := testLoader(c, string(yaml), &logbuf).Load()
266         c.Assert(err, check.IsNil)
267         c.Check(cfg, check.DeepEquals, cfgDumped)
268         c.Check(logbuf.String(), check.Equals, "")
269 }
270
271 func (s *LoadSuite) TestPostgreSQLKeyConflict(c *check.C) {
272         _, err := testLoader(c, `
273 Clusters:
274  zzzzz:
275   postgresql:
276    connection:
277      DBName: dbname
278      Host: host
279 `, nil).Load()
280         c.Check(err, check.ErrorMatches, `Clusters.zzzzz.PostgreSQL.Connection: multiple entries for "(dbname|host)".*`)
281 }
282
283 func (s *LoadSuite) TestBadType(c *check.C) {
284         for _, data := range []string{`
285 Clusters:
286  zzzzz:
287   PostgreSQL: true
288 `, `
289 Clusters:
290  zzzzz:
291   PostgreSQL:
292    ConnectionPool: true
293 `, `
294 Clusters:
295  zzzzz:
296   PostgreSQL:
297    ConnectionPool: "foo"
298 `, `
299 Clusters:
300  zzzzz:
301   PostgreSQL:
302    ConnectionPool: []
303 `, `
304 Clusters:
305  zzzzz:
306   PostgreSQL:
307    ConnectionPool: [] # {foo: bar} isn't caught here; we rely on config-check
308 `,
309         } {
310                 c.Log(data)
311                 v, err := testLoader(c, data, nil).Load()
312                 if v != nil {
313                         c.Logf("%#v", v.Clusters["zzzzz"].PostgreSQL.ConnectionPool)
314                 }
315                 c.Check(err, check.ErrorMatches, `.*cannot unmarshal .*PostgreSQL.*`)
316         }
317 }
318
319 func (s *LoadSuite) TestMovedKeys(c *check.C) {
320         s.checkEquivalent(c, `# config has old keys only
321 Clusters:
322  zzzzz:
323   RequestLimits:
324    MultiClusterRequestConcurrency: 3
325    MaxItemsPerResponse: 999
326 `, `
327 Clusters:
328  zzzzz:
329   API:
330    MaxRequestAmplification: 3
331    MaxItemsPerResponse: 999
332 `)
333         s.checkEquivalent(c, `# config has both old and new keys; old values win
334 Clusters:
335  zzzzz:
336   RequestLimits:
337    MultiClusterRequestConcurrency: 0
338    MaxItemsPerResponse: 555
339   API:
340    MaxRequestAmplification: 3
341    MaxItemsPerResponse: 999
342 `, `
343 Clusters:
344  zzzzz:
345   API:
346    MaxRequestAmplification: 0
347    MaxItemsPerResponse: 555
348 `)
349 }
350
351 func (s *LoadSuite) checkEquivalent(c *check.C, goty, expectedy string) {
352         got, err := testLoader(c, goty, nil).Load()
353         c.Assert(err, check.IsNil)
354         expected, err := testLoader(c, expectedy, nil).Load()
355         c.Assert(err, check.IsNil)
356         if !c.Check(got, check.DeepEquals, expected) {
357                 cmd := exec.Command("diff", "-u", "--label", "expected", "--label", "got", "/dev/fd/3", "/dev/fd/4")
358                 for _, obj := range []interface{}{expected, got} {
359                         y, _ := yaml.Marshal(obj)
360                         pr, pw, err := os.Pipe()
361                         c.Assert(err, check.IsNil)
362                         defer pr.Close()
363                         go func() {
364                                 io.Copy(pw, bytes.NewBuffer(y))
365                                 pw.Close()
366                         }()
367                         cmd.ExtraFiles = append(cmd.ExtraFiles, pr)
368                 }
369                 diff, err := cmd.CombinedOutput()
370                 c.Log(string(diff))
371                 c.Check(err, check.IsNil)
372         }
373 }