16306: Merge branch 'master'
[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.arvados.org/arvados.git/sdk/go/arvados"
19         "git.arvados.org/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) SetUpSuite(c *check.C) {
50         os.Unsetenv("ARVADOS_API_HOST")
51         os.Unsetenv("ARVADOS_API_HOST_INSECURE")
52         os.Unsetenv("ARVADOS_API_TOKEN")
53 }
54
55 func (s *LoadSuite) TestEmpty(c *check.C) {
56         cfg, err := testLoader(c, "", nil).Load()
57         c.Check(cfg, check.IsNil)
58         c.Assert(err, check.ErrorMatches, `config does not define any clusters`)
59 }
60
61 func (s *LoadSuite) TestNoConfigs(c *check.C) {
62         cfg, err := testLoader(c, `Clusters: {"z1111": {}}`, nil).Load()
63         c.Assert(err, check.IsNil)
64         c.Assert(cfg.Clusters, check.HasLen, 1)
65         cc, err := cfg.GetCluster("z1111")
66         c.Assert(err, check.IsNil)
67         c.Check(cc.ClusterID, check.Equals, "z1111")
68         c.Check(cc.API.MaxRequestAmplification, check.Equals, 4)
69         c.Check(cc.API.MaxItemsPerResponse, check.Equals, 1000)
70 }
71
72 func (s *LoadSuite) TestMungeLegacyConfigArgs(c *check.C) {
73         f, err := ioutil.TempFile("", "")
74         c.Check(err, check.IsNil)
75         defer os.Remove(f.Name())
76         io.WriteString(f, "Debug: true\n")
77         oldfile := f.Name()
78
79         f, err = ioutil.TempFile("", "")
80         c.Check(err, check.IsNil)
81         defer os.Remove(f.Name())
82         io.WriteString(f, "Clusters: {aaaaa: {}}\n")
83         newfile := f.Name()
84
85         for _, trial := range []struct {
86                 argsIn  []string
87                 argsOut []string
88         }{
89                 {
90                         []string{"-config", oldfile},
91                         []string{"-old-config", oldfile},
92                 },
93                 {
94                         []string{"-config=" + oldfile},
95                         []string{"-old-config=" + oldfile},
96                 },
97                 {
98                         []string{"-config", newfile},
99                         []string{"-config", newfile},
100                 },
101                 {
102                         []string{"-config=" + newfile},
103                         []string{"-config=" + newfile},
104                 },
105                 {
106                         []string{"-foo", oldfile},
107                         []string{"-foo", oldfile},
108                 },
109                 {
110                         []string{"-foo=" + oldfile},
111                         []string{"-foo=" + oldfile},
112                 },
113                 {
114                         []string{"-foo", "-config=" + oldfile},
115                         []string{"-foo", "-old-config=" + oldfile},
116                 },
117                 {
118                         []string{"-foo", "bar", "-config=" + oldfile},
119                         []string{"-foo", "bar", "-old-config=" + oldfile},
120                 },
121                 {
122                         []string{"-foo=bar", "baz", "-config=" + oldfile},
123                         []string{"-foo=bar", "baz", "-old-config=" + oldfile},
124                 },
125                 {
126                         []string{"-config=/dev/null"},
127                         []string{"-config=/dev/null"},
128                 },
129                 {
130                         []string{"-config=-"},
131                         []string{"-config=-"},
132                 },
133                 {
134                         []string{"-config="},
135                         []string{"-config="},
136                 },
137                 {
138                         []string{"-foo=bar", "baz", "-config"},
139                         []string{"-foo=bar", "baz", "-config"},
140                 },
141                 {
142                         []string{},
143                         nil,
144                 },
145         } {
146                 var logbuf bytes.Buffer
147                 logger := logrus.New()
148                 logger.Out = &logbuf
149
150                 var ldr Loader
151                 args := ldr.MungeLegacyConfigArgs(logger, trial.argsIn, "-old-config")
152                 c.Check(args, check.DeepEquals, trial.argsOut)
153                 if fmt.Sprintf("%v", trial.argsIn) != fmt.Sprintf("%v", trial.argsOut) {
154                         c.Check(logbuf.String(), check.Matches, `.*`+oldfile+` is not a cluster config file -- interpreting -config as -old-config.*\n`)
155                 }
156         }
157 }
158
159 func (s *LoadSuite) TestSampleKeys(c *check.C) {
160         for _, yaml := range []string{
161                 `{"Clusters":{"z1111":{}}}`,
162                 `{"Clusters":{"z1111":{"InstanceTypes":{"Foo":{"RAM": "12345M"}}}}}`,
163         } {
164                 cfg, err := testLoader(c, yaml, nil).Load()
165                 c.Assert(err, check.IsNil)
166                 cc, err := cfg.GetCluster("z1111")
167                 c.Assert(err, check.IsNil)
168                 _, hasSample := cc.InstanceTypes["SAMPLE"]
169                 c.Check(hasSample, check.Equals, false)
170                 if strings.Contains(yaml, "Foo") {
171                         c.Check(cc.InstanceTypes["Foo"].RAM, check.Equals, arvados.ByteSize(12345000000))
172                         c.Check(cc.InstanceTypes["Foo"].Price, check.Equals, 0.0)
173                 }
174         }
175 }
176
177 func (s *LoadSuite) TestMultipleClusters(c *check.C) {
178         ldr := testLoader(c, `{"Clusters":{"z1111":{},"z2222":{}}}`, nil)
179         ldr.SkipDeprecated = true
180         cfg, err := ldr.Load()
181         c.Assert(err, check.IsNil)
182         c1, err := cfg.GetCluster("z1111")
183         c.Assert(err, check.IsNil)
184         c.Check(c1.ClusterID, check.Equals, "z1111")
185         c2, err := cfg.GetCluster("z2222")
186         c.Assert(err, check.IsNil)
187         c.Check(c2.ClusterID, check.Equals, "z2222")
188 }
189
190 func (s *LoadSuite) TestDeprecatedOrUnknownWarning(c *check.C) {
191         var logbuf bytes.Buffer
192         _, err := testLoader(c, `
193 Clusters:
194   zzzzz:
195     ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
196     SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
197     Collections:
198      BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
199     postgresql: {}
200     BadKey: {}
201     Containers: {}
202     RemoteClusters:
203       z2222:
204         Host: z2222.arvadosapi.com
205         Proxy: true
206         BadKey: badValue
207 `, &logbuf).Load()
208         c.Assert(err, check.IsNil)
209         logs := strings.Split(strings.TrimSuffix(logbuf.String(), "\n"), "\n")
210         for _, log := range logs {
211                 c.Check(log, check.Matches, `.*deprecated or unknown config entry:.*BadKey.*`)
212         }
213         c.Check(logs, check.HasLen, 2)
214 }
215
216 func (s *LoadSuite) checkSAMPLEKeys(c *check.C, path string, x interface{}) {
217         v := reflect.Indirect(reflect.ValueOf(x))
218         switch v.Kind() {
219         case reflect.Map:
220                 var stringKeys, sampleKey bool
221                 iter := v.MapRange()
222                 for iter.Next() {
223                         k := iter.Key()
224                         if k.Kind() == reflect.String {
225                                 stringKeys = true
226                                 if k.String() == "SAMPLE" || k.String() == "xxxxx" {
227                                         sampleKey = true
228                                         s.checkSAMPLEKeys(c, path+"."+k.String(), iter.Value().Interface())
229                                 }
230                         }
231                 }
232                 if stringKeys && !sampleKey {
233                         c.Errorf("%s is a map with string keys (type %T) but config.default.yml has no SAMPLE key", path, x)
234                 }
235                 return
236         case reflect.Struct:
237                 for i := 0; i < v.NumField(); i++ {
238                         val := v.Field(i)
239                         if val.CanInterface() {
240                                 s.checkSAMPLEKeys(c, path+"."+v.Type().Field(i).Name, val.Interface())
241                         }
242                 }
243         }
244 }
245
246 func (s *LoadSuite) TestDefaultConfigHasAllSAMPLEKeys(c *check.C) {
247         var logbuf bytes.Buffer
248         loader := testLoader(c, string(DefaultYAML), &logbuf)
249         cfg, err := loader.Load()
250         c.Assert(err, check.IsNil)
251         s.checkSAMPLEKeys(c, "", cfg)
252 }
253
254 func (s *LoadSuite) TestNoUnrecognizedKeysInDefaultConfig(c *check.C) {
255         var logbuf bytes.Buffer
256         var supplied map[string]interface{}
257         yaml.Unmarshal(DefaultYAML, &supplied)
258
259         loader := testLoader(c, string(DefaultYAML), &logbuf)
260         cfg, err := loader.Load()
261         c.Assert(err, check.IsNil)
262         var loaded map[string]interface{}
263         buf, err := yaml.Marshal(cfg)
264         c.Assert(err, check.IsNil)
265         err = yaml.Unmarshal(buf, &loaded)
266         c.Assert(err, check.IsNil)
267
268         c.Check(logbuf.String(), check.Matches, `(?ms).*SystemRootToken: secret token is not set.*`)
269         c.Check(logbuf.String(), check.Matches, `(?ms).*ManagementToken: secret token is not set.*`)
270         c.Check(logbuf.String(), check.Matches, `(?ms).*Collections.BlobSigningKey: secret token is not set.*`)
271         logbuf.Reset()
272         loader.logExtraKeys(loaded, supplied, "")
273         c.Check(logbuf.String(), check.Equals, "")
274 }
275
276 func (s *LoadSuite) TestNoWarningsForDumpedConfig(c *check.C) {
277         var logbuf bytes.Buffer
278         logger := logrus.New()
279         logger.Out = &logbuf
280         cfg, err := testLoader(c, `
281 Clusters:
282  zzzzz:
283   ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
284   SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
285   Collections:
286    BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`, &logbuf).Load()
287         c.Assert(err, check.IsNil)
288         yaml, err := yaml.Marshal(cfg)
289         c.Assert(err, check.IsNil)
290         cfgDumped, err := testLoader(c, string(yaml), &logbuf).Load()
291         c.Assert(err, check.IsNil)
292         c.Check(cfg, check.DeepEquals, cfgDumped)
293         c.Check(logbuf.String(), check.Equals, "")
294 }
295
296 func (s *LoadSuite) TestUnacceptableTokens(c *check.C) {
297         for _, trial := range []struct {
298                 short      bool
299                 configPath string
300                 example    string
301         }{
302                 {false, "SystemRootToken", "SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_b_c"},
303                 {false, "ManagementToken", "ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa b c"},
304                 {false, "ManagementToken", "ManagementToken: \"$aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabc\""},
305                 {false, "Collections.BlobSigningKey", "Collections: {BlobSigningKey: \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa⛵\"}"},
306                 {true, "SystemRootToken", "SystemRootToken: a_b_c"},
307                 {true, "ManagementToken", "ManagementToken: a b c"},
308                 {true, "ManagementToken", "ManagementToken: \"$abc\""},
309                 {true, "Collections.BlobSigningKey", "Collections: {BlobSigningKey: \"⛵\"}"},
310         } {
311                 c.Logf("trying bogus config: %s", trial.example)
312                 _, err := testLoader(c, "Clusters:\n zzzzz:\n  "+trial.example, nil).Load()
313                 if trial.short {
314                         c.Check(err, check.ErrorMatches, `Clusters.zzzzz.`+trial.configPath+`: unacceptable characters in token.*`)
315                 } else {
316                         c.Check(err, check.ErrorMatches, `Clusters.zzzzz.`+trial.configPath+`: unacceptable characters in token.*`)
317                 }
318         }
319 }
320
321 func (s *LoadSuite) TestPostgreSQLKeyConflict(c *check.C) {
322         _, err := testLoader(c, `
323 Clusters:
324  zzzzz:
325   postgresql:
326    connection:
327      DBName: dbname
328      Host: host
329 `, nil).Load()
330         c.Check(err, check.ErrorMatches, `Clusters.zzzzz.PostgreSQL.Connection: multiple entries for "(dbname|host)".*`)
331 }
332
333 func (s *LoadSuite) TestBadType(c *check.C) {
334         for _, data := range []string{`
335 Clusters:
336  zzzzz:
337   PostgreSQL: true
338 `, `
339 Clusters:
340  zzzzz:
341   PostgreSQL:
342    ConnectionPool: true
343 `, `
344 Clusters:
345  zzzzz:
346   PostgreSQL:
347    ConnectionPool: "foo"
348 `, `
349 Clusters:
350  zzzzz:
351   PostgreSQL:
352    ConnectionPool: []
353 `, `
354 Clusters:
355  zzzzz:
356   PostgreSQL:
357    ConnectionPool: [] # {foo: bar} isn't caught here; we rely on config-check
358 `,
359         } {
360                 c.Log(data)
361                 v, err := testLoader(c, data, nil).Load()
362                 if v != nil {
363                         c.Logf("%#v", v.Clusters["zzzzz"].PostgreSQL.ConnectionPool)
364                 }
365                 c.Check(err, check.ErrorMatches, `.*cannot unmarshal .*PostgreSQL.*`)
366         }
367 }
368
369 func (s *LoadSuite) TestMovedKeys(c *check.C) {
370         checkEquivalent(c, `# config has old keys only
371 Clusters:
372  zzzzz:
373   RequestLimits:
374    MultiClusterRequestConcurrency: 3
375    MaxItemsPerResponse: 999
376 `, `
377 Clusters:
378  zzzzz:
379   API:
380    MaxRequestAmplification: 3
381    MaxItemsPerResponse: 999
382 `)
383         checkEquivalent(c, `# config has both old and new keys; old values win
384 Clusters:
385  zzzzz:
386   RequestLimits:
387    MultiClusterRequestConcurrency: 0
388    MaxItemsPerResponse: 555
389   API:
390    MaxRequestAmplification: 3
391    MaxItemsPerResponse: 999
392 `, `
393 Clusters:
394  zzzzz:
395   API:
396    MaxRequestAmplification: 0
397    MaxItemsPerResponse: 555
398 `)
399 }
400
401 func checkEquivalent(c *check.C, goty, expectedy string) {
402         gotldr := testLoader(c, goty, nil)
403         expectedldr := testLoader(c, expectedy, nil)
404         checkEquivalentLoaders(c, gotldr, expectedldr)
405 }
406
407 func checkEqualYAML(c *check.C, got, expected interface{}) {
408         expectedyaml, err := yaml.Marshal(expected)
409         c.Assert(err, check.IsNil)
410         gotyaml, err := yaml.Marshal(got)
411         c.Assert(err, check.IsNil)
412         if !bytes.Equal(gotyaml, expectedyaml) {
413                 cmd := exec.Command("diff", "-u", "--label", "expected", "--label", "got", "/dev/fd/3", "/dev/fd/4")
414                 for _, y := range [][]byte{expectedyaml, gotyaml} {
415                         pr, pw, err := os.Pipe()
416                         c.Assert(err, check.IsNil)
417                         defer pr.Close()
418                         go func(data []byte) {
419                                 pw.Write(data)
420                                 pw.Close()
421                         }(y)
422                         cmd.ExtraFiles = append(cmd.ExtraFiles, pr)
423                 }
424                 diff, err := cmd.CombinedOutput()
425                 // diff should report differences and exit non-zero.
426                 c.Check(err, check.NotNil)
427                 c.Log(string(diff))
428                 c.Error("got != expected; see diff (-expected +got) above")
429         }
430 }
431
432 func checkEquivalentLoaders(c *check.C, gotldr, expectedldr *Loader) {
433         got, err := gotldr.Load()
434         c.Assert(err, check.IsNil)
435         expected, err := expectedldr.Load()
436         c.Assert(err, check.IsNil)
437         checkEqualYAML(c, got, expected)
438 }
439
440 func checkListKeys(path string, x interface{}) (err error) {
441         v := reflect.Indirect(reflect.ValueOf(x))
442         switch v.Kind() {
443         case reflect.Map:
444                 iter := v.MapRange()
445                 for iter.Next() {
446                         k := iter.Key()
447                         if k.Kind() == reflect.String {
448                                 if err = checkListKeys(path+"."+k.String(), iter.Value().Interface()); err != nil {
449                                         return
450                                 }
451                         }
452                 }
453                 return
454
455         case reflect.Struct:
456                 for i := 0; i < v.NumField(); i++ {
457                         val := v.Field(i)
458                         structField := v.Type().Field(i)
459                         fieldname := structField.Name
460                         endsWithList := strings.HasSuffix(fieldname, "List")
461                         isAnArray := structField.Type.Kind() == reflect.Slice
462                         if endsWithList != isAnArray {
463                                 if endsWithList {
464                                         err = fmt.Errorf("%s.%s ends with 'List' but field is not an array (type %v)", path, fieldname, val.Kind())
465                                         return
466                                 }
467                                 if isAnArray && structField.Type.Elem().Kind() != reflect.Uint8 {
468                                         err = fmt.Errorf("%s.%s is an array but field name does not end in 'List' (slice of %v)", path, fieldname, structField.Type.Elem().Kind())
469                                         return
470                                 }
471                         }
472                         if val.CanInterface() {
473                                 checkListKeys(path+"."+fieldname, val.Interface())
474                         }
475                 }
476         }
477         return
478 }
479
480 func (s *LoadSuite) TestListKeys(c *check.C) {
481         v1 := struct {
482                 EndInList []string
483         }{[]string{"a", "b"}}
484         var m1 = make(map[string]interface{})
485         m1["c"] = &v1
486         if err := checkListKeys("", m1); err != nil {
487                 c.Error(err)
488         }
489
490         v2 := struct {
491                 DoesNot []string
492         }{[]string{"a", "b"}}
493         var m2 = make(map[string]interface{})
494         m2["c"] = &v2
495         if err := checkListKeys("", m2); err == nil {
496                 c.Errorf("Should have produced an error")
497         }
498
499         v3 := struct {
500                 EndInList string
501         }{"a"}
502         var m3 = make(map[string]interface{})
503         m3["c"] = &v3
504         if err := checkListKeys("", m3); err == nil {
505                 c.Errorf("Should have produced an error")
506         }
507
508         var logbuf bytes.Buffer
509         loader := testLoader(c, string(DefaultYAML), &logbuf)
510         cfg, err := loader.Load()
511         c.Assert(err, check.IsNil)
512         if err := checkListKeys("", cfg); err != nil {
513                 c.Error(err)
514         }
515 }