Merge branch '18631-shell-login-sync'
[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 var emptyConfigYAML = `Clusters: {"z1111": {}}`
33
34 // Return a new Loader that reads cluster config from configdata
35 // (instead of the usual default /etc/arvados/config.yml), and logs to
36 // logdst or (if that's nil) c.Log.
37 func testLoader(c *check.C, configdata string, logdst io.Writer) *Loader {
38         logger := ctxlog.TestLogger(c)
39         if logdst != nil {
40                 lgr := logrus.New()
41                 lgr.Out = logdst
42                 logger = lgr
43         }
44         ldr := NewLoader(bytes.NewBufferString(configdata), logger)
45         ldr.Path = "-"
46         return ldr
47 }
48
49 type LoadSuite struct{}
50
51 func (s *LoadSuite) SetUpSuite(c *check.C) {
52         os.Unsetenv("ARVADOS_API_HOST")
53         os.Unsetenv("ARVADOS_API_HOST_INSECURE")
54         os.Unsetenv("ARVADOS_API_TOKEN")
55 }
56
57 func (s *LoadSuite) TestEmpty(c *check.C) {
58         cfg, err := testLoader(c, "", nil).Load()
59         c.Check(cfg, check.IsNil)
60         c.Assert(err, check.ErrorMatches, `config does not define any clusters`)
61 }
62
63 func (s *LoadSuite) TestNoConfigs(c *check.C) {
64         cfg, err := testLoader(c, emptyConfigYAML, nil).Load()
65         c.Assert(err, check.IsNil)
66         c.Assert(cfg.Clusters, check.HasLen, 1)
67         cc, err := cfg.GetCluster("z1111")
68         c.Assert(err, check.IsNil)
69         c.Check(cc.ClusterID, check.Equals, "z1111")
70         c.Check(cc.API.MaxRequestAmplification, check.Equals, 4)
71         c.Check(cc.API.MaxItemsPerResponse, check.Equals, 1000)
72 }
73
74 func (s *LoadSuite) TestNullKeyDoesNotOverrideDefault(c *check.C) {
75         ldr := testLoader(c, `{"Clusters":{"z1111":{"API":}}}`, nil)
76         ldr.SkipDeprecated = true
77         cfg, err := ldr.Load()
78         c.Assert(err, check.IsNil)
79         c1, err := cfg.GetCluster("z1111")
80         c.Assert(err, check.IsNil)
81         c.Check(c1.ClusterID, check.Equals, "z1111")
82         c.Check(c1.API.MaxRequestAmplification, check.Equals, 4)
83         c.Check(c1.API.MaxItemsPerResponse, check.Equals, 1000)
84 }
85
86 func (s *LoadSuite) TestMungeLegacyConfigArgs(c *check.C) {
87         f, err := ioutil.TempFile("", "")
88         c.Check(err, check.IsNil)
89         defer os.Remove(f.Name())
90         io.WriteString(f, "Debug: true\n")
91         oldfile := f.Name()
92
93         f, err = ioutil.TempFile("", "")
94         c.Check(err, check.IsNil)
95         defer os.Remove(f.Name())
96         io.WriteString(f, emptyConfigYAML)
97         newfile := f.Name()
98
99         for _, trial := range []struct {
100                 argsIn  []string
101                 argsOut []string
102         }{
103                 {
104                         []string{"-config", oldfile},
105                         []string{"-old-config", oldfile},
106                 },
107                 {
108                         []string{"-config=" + oldfile},
109                         []string{"-old-config=" + oldfile},
110                 },
111                 {
112                         []string{"-config", newfile},
113                         []string{"-config", newfile},
114                 },
115                 {
116                         []string{"-config=" + newfile},
117                         []string{"-config=" + newfile},
118                 },
119                 {
120                         []string{"-foo", oldfile},
121                         []string{"-foo", oldfile},
122                 },
123                 {
124                         []string{"-foo=" + oldfile},
125                         []string{"-foo=" + oldfile},
126                 },
127                 {
128                         []string{"-foo", "-config=" + oldfile},
129                         []string{"-foo", "-old-config=" + oldfile},
130                 },
131                 {
132                         []string{"-foo", "bar", "-config=" + oldfile},
133                         []string{"-foo", "bar", "-old-config=" + oldfile},
134                 },
135                 {
136                         []string{"-foo=bar", "baz", "-config=" + oldfile},
137                         []string{"-foo=bar", "baz", "-old-config=" + oldfile},
138                 },
139                 {
140                         []string{"-config=/dev/null"},
141                         []string{"-config=/dev/null"},
142                 },
143                 {
144                         []string{"-config=-"},
145                         []string{"-config=-"},
146                 },
147                 {
148                         []string{"-config="},
149                         []string{"-config="},
150                 },
151                 {
152                         []string{"-foo=bar", "baz", "-config"},
153                         []string{"-foo=bar", "baz", "-config"},
154                 },
155                 {
156                         []string{},
157                         nil,
158                 },
159         } {
160                 var logbuf bytes.Buffer
161                 logger := logrus.New()
162                 logger.Out = &logbuf
163
164                 var ldr Loader
165                 args := ldr.MungeLegacyConfigArgs(logger, trial.argsIn, "-old-config")
166                 c.Check(args, check.DeepEquals, trial.argsOut)
167                 if fmt.Sprintf("%v", trial.argsIn) != fmt.Sprintf("%v", trial.argsOut) {
168                         c.Check(logbuf.String(), check.Matches, `.*`+oldfile+` is not a cluster config file -- interpreting -config as -old-config.*\n`)
169                 }
170         }
171 }
172
173 func (s *LoadSuite) TestSampleKeys(c *check.C) {
174         for _, yaml := range []string{
175                 `{"Clusters":{"z1111":{}}}`,
176                 `{"Clusters":{"z1111":{"InstanceTypes":{"Foo":{"RAM": "12345M"}}}}}`,
177         } {
178                 cfg, err := testLoader(c, yaml, nil).Load()
179                 c.Assert(err, check.IsNil)
180                 cc, err := cfg.GetCluster("z1111")
181                 c.Assert(err, check.IsNil)
182                 _, hasSample := cc.InstanceTypes["SAMPLE"]
183                 c.Check(hasSample, check.Equals, false)
184                 if strings.Contains(yaml, "Foo") {
185                         c.Check(cc.InstanceTypes["Foo"].RAM, check.Equals, arvados.ByteSize(12345000000))
186                         c.Check(cc.InstanceTypes["Foo"].Price, check.Equals, 0.0)
187                 }
188         }
189 }
190
191 func (s *LoadSuite) TestMultipleClusters(c *check.C) {
192         ldr := testLoader(c, `{"Clusters":{"z1111":{},"z2222":{}}}`, nil)
193         ldr.SkipDeprecated = true
194         cfg, err := ldr.Load()
195         c.Assert(err, check.IsNil)
196         c1, err := cfg.GetCluster("z1111")
197         c.Assert(err, check.IsNil)
198         c.Check(c1.ClusterID, check.Equals, "z1111")
199         c2, err := cfg.GetCluster("z2222")
200         c.Assert(err, check.IsNil)
201         c.Check(c2.ClusterID, check.Equals, "z2222")
202 }
203
204 func (s *LoadSuite) TestDeprecatedOrUnknownWarning(c *check.C) {
205         var logbuf bytes.Buffer
206         _, err := testLoader(c, `
207 Clusters:
208   zzzzz:
209     ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
210     SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
211     Collections:
212      BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
213     PostgreSQL: {}
214     BadKey1: {}
215     Containers:
216       RunTimeEngine: abc
217     RemoteClusters:
218       z2222:
219         Host: z2222.arvadosapi.com
220         Proxy: true
221         BadKey2: badValue
222     Services:
223       KeepStore:
224         InternalURLs:
225           "http://host.example:12345": {}
226       Keepstore:
227         InternalURLs:
228           "http://host.example:12345":
229             RendezVous: x
230     ServiceS:
231       Keepstore:
232         InternalURLs:
233           "http://host.example:12345": {}
234     Volumes:
235       zzzzz-nyw5e-aaaaaaaaaaaaaaa: {}
236 `, &logbuf).Load()
237         c.Assert(err, check.IsNil)
238         c.Log(logbuf.String())
239         logs := strings.Split(strings.TrimSuffix(logbuf.String(), "\n"), "\n")
240         for _, log := range logs {
241                 c.Check(log, check.Matches, `.*deprecated or unknown config entry:.*(RunTimeEngine.*RuntimeEngine|BadKey1|BadKey2|KeepStore|ServiceS|RendezVous).*`)
242         }
243         c.Check(logs, check.HasLen, 6)
244 }
245
246 func (s *LoadSuite) checkSAMPLEKeys(c *check.C, path string, x interface{}) {
247         v := reflect.Indirect(reflect.ValueOf(x))
248         switch v.Kind() {
249         case reflect.Map:
250                 var stringKeys, sampleKey bool
251                 iter := v.MapRange()
252                 for iter.Next() {
253                         k := iter.Key()
254                         if k.Kind() == reflect.String {
255                                 stringKeys = true
256                                 if k.String() == "SAMPLE" || k.String() == "xxxxx" {
257                                         sampleKey = true
258                                         s.checkSAMPLEKeys(c, path+"."+k.String(), iter.Value().Interface())
259                                 }
260                         }
261                 }
262                 if stringKeys && !sampleKey {
263                         c.Errorf("%s is a map with string keys (type %T) but config.default.yml has no SAMPLE key", path, x)
264                 }
265                 return
266         case reflect.Struct:
267                 for i := 0; i < v.NumField(); i++ {
268                         val := v.Field(i)
269                         if val.CanInterface() {
270                                 s.checkSAMPLEKeys(c, path+"."+v.Type().Field(i).Name, val.Interface())
271                         }
272                 }
273         }
274 }
275
276 func (s *LoadSuite) TestDefaultConfigHasAllSAMPLEKeys(c *check.C) {
277         var logbuf bytes.Buffer
278         loader := testLoader(c, string(DefaultYAML), &logbuf)
279         cfg, err := loader.Load()
280         c.Assert(err, check.IsNil)
281         s.checkSAMPLEKeys(c, "", cfg)
282 }
283
284 func (s *LoadSuite) TestNoUnrecognizedKeysInDefaultConfig(c *check.C) {
285         var logbuf bytes.Buffer
286         var supplied map[string]interface{}
287         yaml.Unmarshal(DefaultYAML, &supplied)
288
289         loader := testLoader(c, string(DefaultYAML), &logbuf)
290         cfg, err := loader.Load()
291         c.Assert(err, check.IsNil)
292         var loaded map[string]interface{}
293         buf, err := yaml.Marshal(cfg)
294         c.Assert(err, check.IsNil)
295         err = yaml.Unmarshal(buf, &loaded)
296         c.Assert(err, check.IsNil)
297
298         c.Check(logbuf.String(), check.Matches, `(?ms).*SystemRootToken: secret token is not set.*`)
299         c.Check(logbuf.String(), check.Matches, `(?ms).*ManagementToken: secret token is not set.*`)
300         c.Check(logbuf.String(), check.Matches, `(?ms).*Collections.BlobSigningKey: secret token is not set.*`)
301         logbuf.Reset()
302         loader.logExtraKeys(loaded, supplied, "")
303         c.Check(logbuf.String(), check.Equals, "")
304 }
305
306 func (s *LoadSuite) TestNoWarningsForDumpedConfig(c *check.C) {
307         var logbuf bytes.Buffer
308         cfg, err := testLoader(c, `
309 Clusters:
310  zzzzz:
311   ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
312   SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
313   Collections:
314    BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`, &logbuf).Load()
315         c.Assert(err, check.IsNil)
316         yaml, err := yaml.Marshal(cfg)
317         c.Assert(err, check.IsNil)
318         cfgDumped, err := testLoader(c, string(yaml), &logbuf).Load()
319         c.Assert(err, check.IsNil)
320         c.Check(cfg, check.DeepEquals, cfgDumped)
321         c.Check(logbuf.String(), check.Equals, "")
322 }
323
324 func (s *LoadSuite) TestUnacceptableTokens(c *check.C) {
325         for _, trial := range []struct {
326                 short      bool
327                 configPath string
328                 example    string
329         }{
330                 {false, "SystemRootToken", "SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_b_c"},
331                 {false, "ManagementToken", "ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa b c"},
332                 {false, "ManagementToken", "ManagementToken: \"$aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabc\""},
333                 {false, "Collections.BlobSigningKey", "Collections: {BlobSigningKey: \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa⛵\"}"},
334                 {true, "SystemRootToken", "SystemRootToken: a_b_c"},
335                 {true, "ManagementToken", "ManagementToken: a b c"},
336                 {true, "ManagementToken", "ManagementToken: \"$abc\""},
337                 {true, "Collections.BlobSigningKey", "Collections: {BlobSigningKey: \"⛵\"}"},
338         } {
339                 c.Logf("trying bogus config: %s", trial.example)
340                 _, err := testLoader(c, "Clusters:\n zzzzz:\n  "+trial.example, nil).Load()
341                 if trial.short {
342                         c.Check(err, check.ErrorMatches, `Clusters.zzzzz.`+trial.configPath+`: unacceptable characters in token.*`)
343                 } else {
344                         c.Check(err, check.ErrorMatches, `Clusters.zzzzz.`+trial.configPath+`: unacceptable characters in token.*`)
345                 }
346         }
347 }
348
349 func (s *LoadSuite) TestPostgreSQLKeyConflict(c *check.C) {
350         _, err := testLoader(c, `
351 Clusters:
352  zzzzz:
353   PostgreSQL:
354    Connection:
355      DBName: dbname
356      Host: host
357 `, nil).Load()
358         c.Check(err, check.ErrorMatches, `Clusters.zzzzz.PostgreSQL.Connection: multiple entries for "(dbname|host)".*`)
359 }
360
361 func (s *LoadSuite) TestBadClusterIDs(c *check.C) {
362         for _, data := range []string{`
363 Clusters:
364  123456:
365   ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
366   SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
367   Collections:
368    BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
369 `, `
370 Clusters:
371  12345:
372   ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
373   SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
374   Collections:
375    BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
376   RemoteClusters:
377    Zzzzz:
378     Host: Zzzzz.arvadosapi.com
379     Proxy: true
380 `, `
381 Clusters:
382  abcde:
383   ManagementToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
384   SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
385   Collections:
386    BlobSigningKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
387   Login:
388    LoginCluster: zz-zz
389 `,
390         } {
391                 c.Log(data)
392                 v, err := testLoader(c, data, nil).Load()
393                 if v != nil {
394                         c.Logf("%#v", v.Clusters)
395                 }
396                 c.Check(err, check.ErrorMatches, `.*cluster ID should be 5 alphanumeric characters.*`)
397         }
398 }
399
400 func (s *LoadSuite) TestBadType(c *check.C) {
401         for _, data := range []string{`
402 Clusters:
403  zzzzz:
404   PostgreSQL: true
405 `, `
406 Clusters:
407  zzzzz:
408   PostgreSQL:
409    ConnectionPool: true
410 `, `
411 Clusters:
412  zzzzz:
413   PostgreSQL:
414    ConnectionPool: "foo"
415 `, `
416 Clusters:
417  zzzzz:
418   PostgreSQL:
419    ConnectionPool: []
420 `, `
421 Clusters:
422  zzzzz:
423   PostgreSQL:
424    ConnectionPool: [] # {foo: bar} isn't caught here; we rely on config-check
425 `,
426         } {
427                 c.Log(data)
428                 v, err := testLoader(c, data, nil).Load()
429                 if v != nil {
430                         c.Logf("%#v", v.Clusters["zzzzz"].PostgreSQL.ConnectionPool)
431                 }
432                 c.Check(err, check.ErrorMatches, `.*cannot unmarshal .*PostgreSQL.*`)
433         }
434 }
435
436 func (s *LoadSuite) TestMovedKeys(c *check.C) {
437         checkEquivalent(c, `# config has old keys only
438 Clusters:
439  zzzzz:
440   RequestLimits:
441    MultiClusterRequestConcurrency: 3
442    MaxItemsPerResponse: 999
443 `, `
444 Clusters:
445  zzzzz:
446   API:
447    MaxRequestAmplification: 3
448    MaxItemsPerResponse: 999
449 `)
450         checkEquivalent(c, `# config has both old and new keys; old values win
451 Clusters:
452  zzzzz:
453   RequestLimits:
454    MultiClusterRequestConcurrency: 0
455    MaxItemsPerResponse: 555
456   API:
457    MaxRequestAmplification: 3
458    MaxItemsPerResponse: 999
459 `, `
460 Clusters:
461  zzzzz:
462   API:
463    MaxRequestAmplification: 0
464    MaxItemsPerResponse: 555
465 `)
466 }
467
468 func checkEquivalent(c *check.C, goty, expectedy string) string {
469         var logbuf bytes.Buffer
470         gotldr := testLoader(c, goty, &logbuf)
471         expectedldr := testLoader(c, expectedy, nil)
472         checkEquivalentLoaders(c, gotldr, expectedldr)
473         return logbuf.String()
474 }
475
476 func checkEqualYAML(c *check.C, got, expected interface{}) {
477         expectedyaml, err := yaml.Marshal(expected)
478         c.Assert(err, check.IsNil)
479         gotyaml, err := yaml.Marshal(got)
480         c.Assert(err, check.IsNil)
481         if !bytes.Equal(gotyaml, expectedyaml) {
482                 cmd := exec.Command("diff", "-u", "--label", "expected", "--label", "got", "/dev/fd/3", "/dev/fd/4")
483                 for _, y := range [][]byte{expectedyaml, gotyaml} {
484                         pr, pw, err := os.Pipe()
485                         c.Assert(err, check.IsNil)
486                         defer pr.Close()
487                         go func(data []byte) {
488                                 pw.Write(data)
489                                 pw.Close()
490                         }(y)
491                         cmd.ExtraFiles = append(cmd.ExtraFiles, pr)
492                 }
493                 diff, err := cmd.CombinedOutput()
494                 // diff should report differences and exit non-zero.
495                 c.Check(err, check.NotNil)
496                 c.Log(string(diff))
497                 c.Error("got != expected; see diff (-expected +got) above")
498         }
499 }
500
501 func checkEquivalentLoaders(c *check.C, gotldr, expectedldr *Loader) {
502         got, err := gotldr.Load()
503         c.Assert(err, check.IsNil)
504         expected, err := expectedldr.Load()
505         c.Assert(err, check.IsNil)
506         checkEqualYAML(c, got, expected)
507 }
508
509 func checkListKeys(path string, x interface{}) (err error) {
510         v := reflect.Indirect(reflect.ValueOf(x))
511         switch v.Kind() {
512         case reflect.Map:
513                 iter := v.MapRange()
514                 for iter.Next() {
515                         k := iter.Key()
516                         if k.Kind() == reflect.String {
517                                 if err = checkListKeys(path+"."+k.String(), iter.Value().Interface()); err != nil {
518                                         return
519                                 }
520                         }
521                 }
522                 return
523
524         case reflect.Struct:
525                 for i := 0; i < v.NumField(); i++ {
526                         val := v.Field(i)
527                         structField := v.Type().Field(i)
528                         fieldname := structField.Name
529                         endsWithList := strings.HasSuffix(fieldname, "List")
530                         isAnArray := structField.Type.Kind() == reflect.Slice
531                         if endsWithList != isAnArray {
532                                 if endsWithList {
533                                         err = fmt.Errorf("%s.%s ends with 'List' but field is not an array (type %v)", path, fieldname, val.Kind())
534                                         return
535                                 }
536                                 if isAnArray && structField.Type.Elem().Kind() != reflect.Uint8 {
537                                         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())
538                                         return
539                                 }
540                         }
541                         if val.CanInterface() {
542                                 checkListKeys(path+"."+fieldname, val.Interface())
543                         }
544                 }
545         }
546         return
547 }
548
549 func (s *LoadSuite) TestListKeys(c *check.C) {
550         v1 := struct {
551                 EndInList []string
552         }{[]string{"a", "b"}}
553         var m1 = make(map[string]interface{})
554         m1["c"] = &v1
555         if err := checkListKeys("", m1); err != nil {
556                 c.Error(err)
557         }
558
559         v2 := struct {
560                 DoesNot []string
561         }{[]string{"a", "b"}}
562         var m2 = make(map[string]interface{})
563         m2["c"] = &v2
564         if err := checkListKeys("", m2); err == nil {
565                 c.Errorf("Should have produced an error")
566         }
567
568         v3 := struct {
569                 EndInList string
570         }{"a"}
571         var m3 = make(map[string]interface{})
572         m3["c"] = &v3
573         if err := checkListKeys("", m3); err == nil {
574                 c.Errorf("Should have produced an error")
575         }
576
577         loader := testLoader(c, string(DefaultYAML), nil)
578         cfg, err := loader.Load()
579         c.Assert(err, check.IsNil)
580         if err := checkListKeys("", cfg); err != nil {
581                 c.Error(err)
582         }
583 }
584
585 func (s *LoadSuite) TestImplicitStorageClasses(c *check.C) {
586         // If StorageClasses and Volumes.*.StorageClasses are all
587         // empty, there is a default storage class named "default".
588         ldr := testLoader(c, `{"Clusters":{"z1111":{}}}`, nil)
589         cfg, err := ldr.Load()
590         c.Assert(err, check.IsNil)
591         cc, err := cfg.GetCluster("z1111")
592         c.Assert(err, check.IsNil)
593         c.Check(cc.StorageClasses, check.HasLen, 1)
594         c.Check(cc.StorageClasses["default"].Default, check.Equals, true)
595         c.Check(cc.StorageClasses["default"].Priority, check.Equals, 0)
596
597         // The implicit "default" storage class is used by all
598         // volumes.
599         ldr = testLoader(c, `
600 Clusters:
601  z1111:
602   Volumes:
603    z: {}`, nil)
604         cfg, err = ldr.Load()
605         c.Assert(err, check.IsNil)
606         cc, err = cfg.GetCluster("z1111")
607         c.Assert(err, check.IsNil)
608         c.Check(cc.StorageClasses, check.HasLen, 1)
609         c.Check(cc.StorageClasses["default"].Default, check.Equals, true)
610         c.Check(cc.StorageClasses["default"].Priority, check.Equals, 0)
611         c.Check(cc.Volumes["z"].StorageClasses["default"], check.Equals, true)
612
613         // The "default" storage class isn't implicit if any classes
614         // are configured explicitly.
615         ldr = testLoader(c, `
616 Clusters:
617  z1111:
618   StorageClasses:
619    local:
620     Default: true
621     Priority: 111
622   Volumes:
623    z:
624     StorageClasses:
625      local: true`, nil)
626         cfg, err = ldr.Load()
627         c.Assert(err, check.IsNil)
628         cc, err = cfg.GetCluster("z1111")
629         c.Assert(err, check.IsNil)
630         c.Check(cc.StorageClasses, check.HasLen, 1)
631         c.Check(cc.StorageClasses["local"].Default, check.Equals, true)
632         c.Check(cc.StorageClasses["local"].Priority, check.Equals, 111)
633
634         // It is an error for a volume to refer to a storage class
635         // that isn't listed in StorageClasses.
636         ldr = testLoader(c, `
637 Clusters:
638  z1111:
639   StorageClasses:
640    local:
641     Default: true
642     Priority: 111
643   Volumes:
644    z:
645     StorageClasses:
646      nx: true`, nil)
647         _, err = ldr.Load()
648         c.Assert(err, check.ErrorMatches, `z: volume refers to storage class "nx" that is not defined.*`)
649
650         // It is an error for a volume to refer to a storage class
651         // that isn't listed in StorageClasses ... even if it's
652         // "default", which would exist implicitly if it weren't
653         // referenced explicitly by a volume.
654         ldr = testLoader(c, `
655 Clusters:
656  z1111:
657   Volumes:
658    z:
659     StorageClasses:
660      default: true`, nil)
661         _, err = ldr.Load()
662         c.Assert(err, check.ErrorMatches, `z: volume refers to storage class "default" that is not defined.*`)
663
664         // If the "default" storage class is configured explicitly, it
665         // is not used implicitly by any volumes, even if it's the
666         // only storage class.
667         var logbuf bytes.Buffer
668         ldr = testLoader(c, `
669 Clusters:
670  z1111:
671   StorageClasses:
672    default:
673     Default: true
674     Priority: 111
675   Volumes:
676    z: {}`, &logbuf)
677         _, err = ldr.Load()
678         c.Assert(err, check.ErrorMatches, `z: volume has no StorageClasses listed`)
679
680         // If StorageClasses are configured explicitly, there must be
681         // at least one with Default: true. (Calling one "default" is
682         // not sufficient.)
683         ldr = testLoader(c, `
684 Clusters:
685  z1111:
686   StorageClasses:
687    default:
688     Priority: 111
689   Volumes:
690    z:
691     StorageClasses:
692      default: true`, nil)
693         _, err = ldr.Load()
694         c.Assert(err, check.ErrorMatches, `there is no default storage class.*`)
695 }
696
697 func (s *LoadSuite) TestPreemptiblePriceFactor(c *check.C) {
698         yaml := `
699 Clusters:
700  z1111:
701   InstanceTypes:
702    Type1:
703     RAM: 12345M
704     VCPUs: 8
705     Price: 1.23
706  z2222:
707   Containers:
708    PreemptiblePriceFactor: 0.5
709   InstanceTypes:
710    Type1:
711     RAM: 12345M
712     VCPUs: 8
713     Price: 1.23
714  z3333:
715   Containers:
716    PreemptiblePriceFactor: 0.5
717   InstanceTypes:
718    Type1:
719     RAM: 12345M
720     VCPUs: 8
721     Price: 1.23
722    Type1.preemptible: # higher price than the auto-added variant would use -- should generate warning
723     ProviderType: Type1
724     RAM: 12345M
725     VCPUs: 8
726     Price: 1.23
727     Preemptible: true
728    Type2:
729     RAM: 23456M
730     VCPUs: 16
731     Price: 2.46
732    Type2.preemptible: # identical to the auto-added variant -- so no warning
733     ProviderType: Type2
734     RAM: 23456M
735     VCPUs: 16
736     Price: 1.23
737     Preemptible: true
738 `
739         var logbuf bytes.Buffer
740         cfg, err := testLoader(c, yaml, &logbuf).Load()
741         c.Assert(err, check.IsNil)
742         cc, err := cfg.GetCluster("z1111")
743         c.Assert(err, check.IsNil)
744         c.Check(cc.InstanceTypes["Type1"].Price, check.Equals, 1.23)
745         c.Check(cc.InstanceTypes, check.HasLen, 1)
746
747         cc, err = cfg.GetCluster("z2222")
748         c.Assert(err, check.IsNil)
749         c.Check(cc.InstanceTypes["Type1"].Preemptible, check.Equals, false)
750         c.Check(cc.InstanceTypes["Type1"].Price, check.Equals, 1.23)
751         c.Check(cc.InstanceTypes["Type1.preemptible"].Preemptible, check.Equals, true)
752         c.Check(cc.InstanceTypes["Type1.preemptible"].Price, check.Equals, 1.23/2)
753         c.Check(cc.InstanceTypes["Type1.preemptible"].ProviderType, check.Equals, "Type1")
754         c.Check(cc.InstanceTypes, check.HasLen, 2)
755
756         cc, err = cfg.GetCluster("z3333")
757         c.Assert(err, check.IsNil)
758         // Don't overwrite the explicitly configured preemptible variant
759         c.Check(cc.InstanceTypes["Type1.preemptible"].Price, check.Equals, 1.23)
760         c.Check(cc.InstanceTypes, check.HasLen, 4)
761         c.Check(logbuf.String(), check.Matches, `(?ms).*Clusters\.z3333\.InstanceTypes\[Type1\.preemptible\]: already exists, so not automatically adding a preemptible variant of Type1.*`)
762         c.Check(logbuf.String(), check.Not(check.Matches), `(?ms).*Type2\.preemptible.*`)
763         c.Check(logbuf.String(), check.Not(check.Matches), `(?ms).*(z1111|z2222)[^\n]*InstanceTypes.*`)
764 }