1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
25 // Gocheck boilerplate
26 func Test(t *testing.T) {
30 var _ = check.Suite(&LoadSuite{})
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)
42 ldr := NewLoader(bytes.NewBufferString(configdata), logger)
47 type LoadSuite struct{}
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")
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`)
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)
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")
79 f, err = ioutil.TempFile("", "")
80 c.Check(err, check.IsNil)
81 defer os.Remove(f.Name())
82 io.WriteString(f, "Clusters: {aaaaa: {}}\n")
85 for _, trial := range []struct {
90 []string{"-config", oldfile},
91 []string{"-old-config", oldfile},
94 []string{"-config=" + oldfile},
95 []string{"-old-config=" + oldfile},
98 []string{"-config", newfile},
99 []string{"-config", newfile},
102 []string{"-config=" + newfile},
103 []string{"-config=" + newfile},
106 []string{"-foo", oldfile},
107 []string{"-foo", oldfile},
110 []string{"-foo=" + oldfile},
111 []string{"-foo=" + oldfile},
114 []string{"-foo", "-config=" + oldfile},
115 []string{"-foo", "-old-config=" + oldfile},
118 []string{"-foo", "bar", "-config=" + oldfile},
119 []string{"-foo", "bar", "-old-config=" + oldfile},
122 []string{"-foo=bar", "baz", "-config=" + oldfile},
123 []string{"-foo=bar", "baz", "-old-config=" + oldfile},
126 []string{"-config=/dev/null"},
127 []string{"-config=/dev/null"},
130 []string{"-config=-"},
131 []string{"-config=-"},
134 []string{"-config="},
135 []string{"-config="},
138 []string{"-foo=bar", "baz", "-config"},
139 []string{"-foo=bar", "baz", "-config"},
146 var logbuf bytes.Buffer
147 logger := logrus.New()
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`)
159 func (s *LoadSuite) TestSampleKeys(c *check.C) {
160 for _, yaml := range []string{
161 `{"Clusters":{"z1111":{}}}`,
162 `{"Clusters":{"z1111":{"InstanceTypes":{"Foo":{"RAM": "12345M"}}}}}`,
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)
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")
190 func (s *LoadSuite) TestDeprecatedOrUnknownWarning(c *check.C) {
191 var logbuf bytes.Buffer
192 _, err := testLoader(c, `
195 ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
196 SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
198 BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
205 Host: z2222.arvadosapi.com
211 "http://host.example:12345": {}
214 "http://host.example:12345":
219 "http://host.example:12345": {}
221 zzzzz-nyw5e-aaaaaaaaaaaaaaa: {}
223 c.Assert(err, check.IsNil)
224 c.Log(logbuf.String())
225 logs := strings.Split(strings.TrimSuffix(logbuf.String(), "\n"), "\n")
226 for _, log := range logs {
227 c.Check(log, check.Matches, `.*deprecated or unknown config entry:.*(RunTimeEngine.*RuntimeEngine|BadKey1|BadKey2|KeepStore|ServiceS|RendezVous).*`)
229 c.Check(logs, check.HasLen, 6)
232 func (s *LoadSuite) checkSAMPLEKeys(c *check.C, path string, x interface{}) {
233 v := reflect.Indirect(reflect.ValueOf(x))
236 var stringKeys, sampleKey bool
240 if k.Kind() == reflect.String {
242 if k.String() == "SAMPLE" || k.String() == "xxxxx" {
244 s.checkSAMPLEKeys(c, path+"."+k.String(), iter.Value().Interface())
248 if stringKeys && !sampleKey {
249 c.Errorf("%s is a map with string keys (type %T) but config.default.yml has no SAMPLE key", path, x)
253 for i := 0; i < v.NumField(); i++ {
255 if val.CanInterface() {
256 s.checkSAMPLEKeys(c, path+"."+v.Type().Field(i).Name, val.Interface())
262 func (s *LoadSuite) TestDefaultConfigHasAllSAMPLEKeys(c *check.C) {
263 var logbuf bytes.Buffer
264 loader := testLoader(c, string(DefaultYAML), &logbuf)
265 cfg, err := loader.Load()
266 c.Assert(err, check.IsNil)
267 s.checkSAMPLEKeys(c, "", cfg)
270 func (s *LoadSuite) TestNoUnrecognizedKeysInDefaultConfig(c *check.C) {
271 var logbuf bytes.Buffer
272 var supplied map[string]interface{}
273 yaml.Unmarshal(DefaultYAML, &supplied)
275 loader := testLoader(c, string(DefaultYAML), &logbuf)
276 cfg, err := loader.Load()
277 c.Assert(err, check.IsNil)
278 var loaded map[string]interface{}
279 buf, err := yaml.Marshal(cfg)
280 c.Assert(err, check.IsNil)
281 err = yaml.Unmarshal(buf, &loaded)
282 c.Assert(err, check.IsNil)
284 c.Check(logbuf.String(), check.Matches, `(?ms).*SystemRootToken: secret token is not set.*`)
285 c.Check(logbuf.String(), check.Matches, `(?ms).*ManagementToken: secret token is not set.*`)
286 c.Check(logbuf.String(), check.Matches, `(?ms).*Collections.BlobSigningKey: secret token is not set.*`)
288 loader.logExtraKeys(loaded, supplied, "")
289 c.Check(logbuf.String(), check.Equals, "")
292 func (s *LoadSuite) TestNoWarningsForDumpedConfig(c *check.C) {
293 var logbuf bytes.Buffer
294 logger := logrus.New()
296 cfg, err := testLoader(c, `
299 ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
300 SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
302 BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`, &logbuf).Load()
303 c.Assert(err, check.IsNil)
304 yaml, err := yaml.Marshal(cfg)
305 c.Assert(err, check.IsNil)
306 cfgDumped, err := testLoader(c, string(yaml), &logbuf).Load()
307 c.Assert(err, check.IsNil)
308 c.Check(cfg, check.DeepEquals, cfgDumped)
309 c.Check(logbuf.String(), check.Equals, "")
312 func (s *LoadSuite) TestUnacceptableTokens(c *check.C) {
313 for _, trial := range []struct {
318 {false, "SystemRootToken", "SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_b_c"},
319 {false, "ManagementToken", "ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa b c"},
320 {false, "ManagementToken", "ManagementToken: \"$aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabc\""},
321 {false, "Collections.BlobSigningKey", "Collections: {BlobSigningKey: \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa⛵\"}"},
322 {true, "SystemRootToken", "SystemRootToken: a_b_c"},
323 {true, "ManagementToken", "ManagementToken: a b c"},
324 {true, "ManagementToken", "ManagementToken: \"$abc\""},
325 {true, "Collections.BlobSigningKey", "Collections: {BlobSigningKey: \"⛵\"}"},
327 c.Logf("trying bogus config: %s", trial.example)
328 _, err := testLoader(c, "Clusters:\n zzzzz:\n "+trial.example, nil).Load()
330 c.Check(err, check.ErrorMatches, `Clusters.zzzzz.`+trial.configPath+`: unacceptable characters in token.*`)
332 c.Check(err, check.ErrorMatches, `Clusters.zzzzz.`+trial.configPath+`: unacceptable characters in token.*`)
337 func (s *LoadSuite) TestPostgreSQLKeyConflict(c *check.C) {
338 _, err := testLoader(c, `
346 c.Check(err, check.ErrorMatches, `Clusters.zzzzz.PostgreSQL.Connection: multiple entries for "(dbname|host)".*`)
349 func (s *LoadSuite) TestBadClusterIDs(c *check.C) {
350 for _, data := range []string{`
353 ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
354 SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
356 BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
360 ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
361 SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
363 BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
366 Host: Zzzzz.arvadosapi.com
371 ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
372 SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
374 BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
380 v, err := testLoader(c, data, nil).Load()
382 c.Logf("%#v", v.Clusters)
384 c.Check(err, check.ErrorMatches, `.*cluster ID should be 5 alphanumeric characters.*`)
388 func (s *LoadSuite) TestBadType(c *check.C) {
389 for _, data := range []string{`
402 ConnectionPool: "foo"
412 ConnectionPool: [] # {foo: bar} isn't caught here; we rely on config-check
416 v, err := testLoader(c, data, nil).Load()
418 c.Logf("%#v", v.Clusters["zzzzz"].PostgreSQL.ConnectionPool)
420 c.Check(err, check.ErrorMatches, `.*cannot unmarshal .*PostgreSQL.*`)
424 func (s *LoadSuite) TestMovedKeys(c *check.C) {
425 checkEquivalent(c, `# config has old keys only
429 MultiClusterRequestConcurrency: 3
430 MaxItemsPerResponse: 999
435 MaxRequestAmplification: 3
436 MaxItemsPerResponse: 999
438 checkEquivalent(c, `# config has both old and new keys; old values win
442 MultiClusterRequestConcurrency: 0
443 MaxItemsPerResponse: 555
445 MaxRequestAmplification: 3
446 MaxItemsPerResponse: 999
451 MaxRequestAmplification: 0
452 MaxItemsPerResponse: 555
456 func checkEquivalent(c *check.C, goty, expectedy string) string {
457 var logbuf bytes.Buffer
458 gotldr := testLoader(c, goty, &logbuf)
459 expectedldr := testLoader(c, expectedy, nil)
460 checkEquivalentLoaders(c, gotldr, expectedldr)
461 return logbuf.String()
464 func checkEqualYAML(c *check.C, got, expected interface{}) {
465 expectedyaml, err := yaml.Marshal(expected)
466 c.Assert(err, check.IsNil)
467 gotyaml, err := yaml.Marshal(got)
468 c.Assert(err, check.IsNil)
469 if !bytes.Equal(gotyaml, expectedyaml) {
470 cmd := exec.Command("diff", "-u", "--label", "expected", "--label", "got", "/dev/fd/3", "/dev/fd/4")
471 for _, y := range [][]byte{expectedyaml, gotyaml} {
472 pr, pw, err := os.Pipe()
473 c.Assert(err, check.IsNil)
475 go func(data []byte) {
479 cmd.ExtraFiles = append(cmd.ExtraFiles, pr)
481 diff, err := cmd.CombinedOutput()
482 // diff should report differences and exit non-zero.
483 c.Check(err, check.NotNil)
485 c.Error("got != expected; see diff (-expected +got) above")
489 func checkEquivalentLoaders(c *check.C, gotldr, expectedldr *Loader) {
490 got, err := gotldr.Load()
491 c.Assert(err, check.IsNil)
492 expected, err := expectedldr.Load()
493 c.Assert(err, check.IsNil)
494 checkEqualYAML(c, got, expected)
497 func checkListKeys(path string, x interface{}) (err error) {
498 v := reflect.Indirect(reflect.ValueOf(x))
504 if k.Kind() == reflect.String {
505 if err = checkListKeys(path+"."+k.String(), iter.Value().Interface()); err != nil {
513 for i := 0; i < v.NumField(); i++ {
515 structField := v.Type().Field(i)
516 fieldname := structField.Name
517 endsWithList := strings.HasSuffix(fieldname, "List")
518 isAnArray := structField.Type.Kind() == reflect.Slice
519 if endsWithList != isAnArray {
521 err = fmt.Errorf("%s.%s ends with 'List' but field is not an array (type %v)", path, fieldname, val.Kind())
524 if isAnArray && structField.Type.Elem().Kind() != reflect.Uint8 {
525 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())
529 if val.CanInterface() {
530 checkListKeys(path+"."+fieldname, val.Interface())
537 func (s *LoadSuite) TestListKeys(c *check.C) {
540 }{[]string{"a", "b"}}
541 var m1 = make(map[string]interface{})
543 if err := checkListKeys("", m1); err != nil {
549 }{[]string{"a", "b"}}
550 var m2 = make(map[string]interface{})
552 if err := checkListKeys("", m2); err == nil {
553 c.Errorf("Should have produced an error")
559 var m3 = make(map[string]interface{})
561 if err := checkListKeys("", m3); err == nil {
562 c.Errorf("Should have produced an error")
565 var logbuf bytes.Buffer
566 loader := testLoader(c, string(DefaultYAML), &logbuf)
567 cfg, err := loader.Load()
568 c.Assert(err, check.IsNil)
569 if err := checkListKeys("", cfg); err != nil {