forked from canonical/snapd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_test.go
3920 lines (3384 loc) · 111 KB
/
image_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2014-2022 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package image_test
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"testing"
"time"
. "gopkg.in/check.v1"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/asserts/assertstest"
"github.com/snapcore/snapd/asserts/sysdb"
"github.com/snapcore/snapd/bootloader"
"github.com/snapcore/snapd/bootloader/assets"
"github.com/snapcore/snapd/bootloader/bootloadertest"
"github.com/snapcore/snapd/bootloader/grubenv"
"github.com/snapcore/snapd/bootloader/ubootenv"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/gadget"
"github.com/snapcore/snapd/image"
"github.com/snapcore/snapd/image/preseed"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/overlord/auth"
"github.com/snapcore/snapd/progress"
"github.com/snapcore/snapd/seed"
"github.com/snapcore/snapd/seed/seedtest"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/snaptest"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/store/tooling"
"github.com/snapcore/snapd/testutil"
"github.com/snapcore/snapd/timings"
)
func Test(t *testing.T) { TestingT(t) }
type imageSuite struct {
testutil.BaseTest
root string
bootloader *bootloadertest.MockBootloader
stdout *bytes.Buffer
stderr *bytes.Buffer
storeActionsBunchSizes []int
storeActions []*store.SnapAction
curSnaps [][]*store.CurrentSnap
tsto *tooling.ToolingStore
// SeedSnaps helps creating and making available seed snaps
// (it provides MakeAssertedSnap etc.) for the tests.
*seedtest.SeedSnaps
model *asserts.Model
}
var _ = Suite(&imageSuite{})
var (
brandPrivKey, _ = assertstest.GenerateKey(752)
)
func (s *imageSuite) SetUpTest(c *C) {
s.root = c.MkDir()
s.bootloader = bootloadertest.Mock("grub", c.MkDir())
bootloader.Force(s.bootloader)
s.BaseTest.SetUpTest(c)
s.BaseTest.AddCleanup(snap.MockSanitizePlugsSlots(func(snapInfo *snap.Info) {}))
s.stdout = &bytes.Buffer{}
image.Stdout = s.stdout
s.stderr = &bytes.Buffer{}
image.Stderr = s.stderr
s.tsto = tooling.MockToolingStore(s)
s.SeedSnaps = &seedtest.SeedSnaps{}
s.SetupAssertSigning("canonical")
s.Brands.Register("my-brand", brandPrivKey, map[string]interface{}{
"verification": "verified",
})
assertstest.AddMany(s.StoreSigning, s.Brands.AccountsAndKeys("my-brand")...)
s.model = s.Brands.Model("my-brand", "my-model", map[string]interface{}{
"display-name": "my display name",
"architecture": "amd64",
"gadget": "pc",
"kernel": "pc-kernel",
"required-snaps": []interface{}{"required-snap1"},
})
otherAcct := assertstest.NewAccount(s.StoreSigning, "other", map[string]interface{}{
"account-id": "other",
}, "")
s.StoreSigning.Add(otherAcct)
// mock the mount cmds (for the extract kernel assets stuff)
c1 := testutil.MockCommand(c, "mount", "")
s.AddCleanup(c1.Restore)
c2 := testutil.MockCommand(c, "umount", "")
s.AddCleanup(c2.Restore)
restore := image.MockWriteResolvedContent(func(_ string, _ *gadget.Info, _, _ string) error {
return nil
})
s.AddCleanup(restore)
}
func (s *imageSuite) TearDownTest(c *C) {
s.BaseTest.TearDownTest(c)
bootloader.Force(nil)
image.Stdout = os.Stdout
image.Stderr = os.Stderr
s.storeActions = nil
s.storeActionsBunchSizes = nil
s.curSnaps = nil
}
// interface for the store
func (s *imageSuite) SnapAction(_ context.Context, curSnaps []*store.CurrentSnap, actions []*store.SnapAction, assertQuery store.AssertionQuery, _ *auth.UserState, _ *store.RefreshOptions) ([]store.SnapActionResult, []store.AssertionResult, error) {
if assertQuery != nil {
return nil, nil, fmt.Errorf("unexpected assertion query")
}
s.storeActionsBunchSizes = append(s.storeActionsBunchSizes, len(actions))
s.curSnaps = append(s.curSnaps, curSnaps)
sars := make([]store.SnapActionResult, 0, len(actions))
for _, a := range actions {
if a.Action != "download" {
return nil, nil, fmt.Errorf("unexpected action %q", a.Action)
}
if _, instanceKey := snap.SplitInstanceName(a.InstanceName); instanceKey != "" {
return nil, nil, fmt.Errorf("unexpected instance key in %q", a.InstanceName)
}
// record
s.storeActions = append(s.storeActions, a)
info := s.AssertedSnapInfo(a.InstanceName)
if info == nil {
return nil, nil, fmt.Errorf("no %q in the fake store", a.InstanceName)
}
info1 := *info
channel := a.Channel
redirectChannel := ""
if strings.HasPrefix(a.InstanceName, "default-track-") {
channel = "default-track/stable"
redirectChannel = channel
}
info1.Channel = channel
sars = append(sars, store.SnapActionResult{
Info: &info1,
RedirectChannel: redirectChannel,
})
}
return sars, nil, nil
}
func (s *imageSuite) Download(ctx context.Context, name, targetFn string, downloadInfo *snap.DownloadInfo, pbar progress.Meter, user *auth.UserState, dlOpts *store.DownloadOptions) error {
return osutil.CopyFile(s.AssertedSnap(name), targetFn, 0)
}
func (s *imageSuite) Assertion(assertType *asserts.AssertionType, primaryKey []string, user *auth.UserState) (asserts.Assertion, error) {
ref := &asserts.Ref{Type: assertType, PrimaryKey: primaryKey}
return ref.Resolve(s.StoreSigning.Find)
}
// TODO: use seedtest.SampleSnapYaml for some of these
const packageGadget = `
name: pc
version: 1.0
type: gadget
`
const packageGadgetWithBase = `
name: pc18
version: 1.0
type: gadget
base: core18
`
const packageClassicGadget = `
name: classic-gadget
version: 1.0
type: gadget
`
const packageClassicGadget18 = `
name: classic-gadget18
version: 1.0
type: gadget
base: core18
`
const packageKernel = `
name: pc-kernel
version: 4.4-1
type: kernel
`
const packageCore = `
name: core
version: 16.04
type: os
`
const packageCore18 = `
name: core18
version: 18.04
type: base
`
const snapdSnap = `
name: snapd
version: 3.14
type: snapd
`
const otherBase = `
name: other-base
version: 2.5029
type: base
`
const devmodeSnap = `
name: devmode-snap
version: 1.0
type: app
confinement: devmode
`
const classicSnap = `
name: classic-snap
version: 1.0
type: app
confinement: classic
`
const requiredSnap1 = `
name: required-snap1
version: 1.0
`
const requiredSnap18 = `
name: required-snap18
version: 1.0
base: core18
`
const defaultTrackSnap18 = `
name: default-track-snap18
version: 1.0
base: core18
`
const snapReqOtherBase = `
name: snap-req-other-base
version: 1.0
base: other-base
`
const snapReqCore16Base = `
name: snap-req-core16-base
version: 1.0
base: core16
`
const snapReqContentProvider = `
name: snap-req-content-provider
version: 1.0
plugs:
gtk-3-themes:
interface: content
default-provider: gtk-common-themes
target: $SNAP/data-dir/themes
`
const snapBaseNone = `
name: snap-base-none
version: 1.0
base: none
`
func (s *imageSuite) TestMissingModelAssertions(c *C) {
_, err := image.DecodeModelAssertion(&image.Options{})
c.Assert(err, ErrorMatches, "cannot read model assertion: open : no such file or directory")
}
func (s *imageSuite) TestIncorrectModelAssertions(c *C) {
fn := filepath.Join(c.MkDir(), "broken-model.assertion")
err := ioutil.WriteFile(fn, nil, 0644)
c.Assert(err, IsNil)
_, err = image.DecodeModelAssertion(&image.Options{
ModelFile: fn,
})
c.Assert(err, ErrorMatches, fmt.Sprintf(`cannot decode model assertion "%s": assertion content/signature separator not found`, fn))
}
func (s *imageSuite) TestValidButDifferentAssertion(c *C) {
var differentAssertion = []byte(`type: snap-declaration
authority-id: canonical
series: 16
snap-id: snap-id-1
snap-name: first
publisher-id: dev-id1
timestamp: 2016-01-02T10:00:00-05:00
sign-key-sha3-384: Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij
AXNpZw==
`)
fn := filepath.Join(c.MkDir(), "different.assertion")
err := ioutil.WriteFile(fn, differentAssertion, 0644)
c.Assert(err, IsNil)
_, err = image.DecodeModelAssertion(&image.Options{
ModelFile: fn,
})
c.Assert(err, ErrorMatches, fmt.Sprintf(`assertion in "%s" is not a model assertion`, fn))
}
func (s *imageSuite) TestModelAssertionReservedHeaders(c *C) {
const mod = `type: model
authority-id: brand
series: 16
brand-id: brand
model: baz-3000
architecture: armhf
gadget: brand-gadget
kernel: kernel
timestamp: 2016-01-02T10:00:00-05:00
sign-key-sha3-384: Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij
AXNpZw==
`
reserved := []string{
"core",
"os",
"class",
"allowed-modes",
}
for _, rsvd := range reserved {
tweaked := strings.Replace(mod, "kernel: kernel\n", fmt.Sprintf("kernel: kernel\n%s: stuff\n", rsvd), 1)
fn := filepath.Join(c.MkDir(), "model.assertion")
err := ioutil.WriteFile(fn, []byte(tweaked), 0644)
c.Assert(err, IsNil)
_, err = image.DecodeModelAssertion(&image.Options{
ModelFile: fn,
})
c.Check(err, ErrorMatches, fmt.Sprintf("model assertion cannot have reserved/unsupported header %q set", rsvd))
}
}
func (s *imageSuite) TestModelAssertionNoParallelInstancesOfSnaps(c *C) {
const mod = `type: model
authority-id: brand
series: 16
brand-id: brand
model: baz-3000
architecture: armhf
gadget: brand-gadget
kernel: kernel
required-snaps:
- foo_instance
timestamp: 2016-01-02T10:00:00-05:00
sign-key-sha3-384: Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij
AXNpZw==
`
fn := filepath.Join(c.MkDir(), "model.assertion")
err := ioutil.WriteFile(fn, []byte(mod), 0644)
c.Assert(err, IsNil)
_, err = image.DecodeModelAssertion(&image.Options{
ModelFile: fn,
})
c.Check(err, ErrorMatches, `.* assertion model: invalid snap name in "required-snaps" header: foo_instance`)
}
func (s *imageSuite) TestModelAssertionNoParallelInstancesOfKernel(c *C) {
const mod = `type: model
authority-id: brand
series: 16
brand-id: brand
model: baz-3000
architecture: armhf
gadget: brand-gadget
kernel: kernel_instance
timestamp: 2016-01-02T10:00:00-05:00
sign-key-sha3-384: Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij
AXNpZw==
`
fn := filepath.Join(c.MkDir(), "model.assertion")
err := ioutil.WriteFile(fn, []byte(mod), 0644)
c.Assert(err, IsNil)
_, err = image.DecodeModelAssertion(&image.Options{
ModelFile: fn,
})
c.Check(err, ErrorMatches, `.* assertion model: invalid snap name in "kernel" header: kernel_instance`)
}
func (s *imageSuite) TestModelAssertionNoParallelInstancesOfGadget(c *C) {
const mod = `type: model
authority-id: brand
series: 16
brand-id: brand
model: baz-3000
architecture: armhf
gadget: brand-gadget_instance
kernel: kernel
timestamp: 2016-01-02T10:00:00-05:00
sign-key-sha3-384: Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij
AXNpZw==
`
fn := filepath.Join(c.MkDir(), "model.assertion")
err := ioutil.WriteFile(fn, []byte(mod), 0644)
c.Assert(err, IsNil)
_, err = image.DecodeModelAssertion(&image.Options{
ModelFile: fn,
})
c.Check(err, ErrorMatches, `.* assertion model: invalid snap name in "gadget" header: brand-gadget_instance`)
}
func (s *imageSuite) TestModelAssertionNoParallelInstancesOfBase(c *C) {
const mod = `type: model
authority-id: brand
series: 16
brand-id: brand
model: baz-3000
architecture: armhf
gadget: brand-gadget
kernel: kernel
base: core18_instance
timestamp: 2016-01-02T10:00:00-05:00
sign-key-sha3-384: Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij
AXNpZw==
`
fn := filepath.Join(c.MkDir(), "model.assertion")
err := ioutil.WriteFile(fn, []byte(mod), 0644)
c.Assert(err, IsNil)
_, err = image.DecodeModelAssertion(&image.Options{
ModelFile: fn,
})
c.Check(err, ErrorMatches, `.* assertion model: invalid snap name in "base" header: core18_instance`)
}
func (s *imageSuite) TestHappyDecodeModelAssertion(c *C) {
fn := filepath.Join(c.MkDir(), "model.assertion")
err := ioutil.WriteFile(fn, asserts.Encode(s.model), 0644)
c.Assert(err, IsNil)
a, err := image.DecodeModelAssertion(&image.Options{
ModelFile: fn,
})
c.Assert(err, IsNil)
c.Check(a.Type(), Equals, asserts.ModelType)
}
func (s *imageSuite) MakeAssertedSnap(c *C, snapYaml string, files [][]string, revision snap.Revision, developerID string) {
s.SeedSnaps.MakeAssertedSnap(c, snapYaml, files, revision, developerID, s.StoreSigning.Database)
}
const stableChannel = "stable"
const pcGadgetYaml = `
volumes:
pc:
bootloader: grub
`
const pcUC20GadgetYaml = `
volumes:
pc:
bootloader: grub
structure:
- name: ubuntu-seed
role: system-seed
type: EF,C12A7328-F81F-11D2-BA4B-00A0C93EC93B
size: 100M
- name: ubuntu-data
role: system-data
type: 83,0FC63DAF-8483-4772-8E79-3D69D8477DE4
size: 200M
`
const piUC20GadgetYaml = `
volumes:
pi:
schema: mbr
bootloader: u-boot
structure:
- name: ubuntu-seed
role: system-seed
type: 0C
size: 100M
- name: ubuntu-data
role: system-data
type: 83,0FC63DAF-8483-4772-8E79-3D69D8477DE4
size: 200M
`
func (s *imageSuite) setupSnaps(c *C, publishers map[string]string, defaultsYaml string) {
gadgetYaml := pcGadgetYaml + defaultsYaml
if _, ok := publishers["pc"]; ok {
s.MakeAssertedSnap(c, packageGadget, [][]string{
{"grub.conf", ""}, {"grub.cfg", "I'm a grub.cfg"},
{"meta/gadget.yaml", gadgetYaml},
}, snap.R(1), publishers["pc"])
}
if _, ok := publishers["pc18"]; ok {
s.MakeAssertedSnap(c, packageGadgetWithBase, [][]string{
{"grub.conf", ""}, {"grub.cfg", "I'm a grub.cfg"},
{"meta/gadget.yaml", gadgetYaml},
}, snap.R(4), publishers["pc18"])
}
if _, ok := publishers["classic-gadget"]; ok {
s.MakeAssertedSnap(c, packageClassicGadget, [][]string{
{"some-file", "Some file"},
}, snap.R(5), publishers["classic-gadget"])
}
if _, ok := publishers["classic-gadget18"]; ok {
s.MakeAssertedSnap(c, packageClassicGadget18, [][]string{
{"some-file", "Some file"},
}, snap.R(5), publishers["classic-gadget18"])
}
if _, ok := publishers["pc-kernel"]; ok {
s.MakeAssertedSnap(c, packageKernel, nil, snap.R(2), publishers["pc-kernel"])
}
s.MakeAssertedSnap(c, packageCore, nil, snap.R(3), "canonical")
s.MakeAssertedSnap(c, packageCore18, nil, snap.R(18), "canonical")
s.MakeAssertedSnap(c, snapdSnap, nil, snap.R(18), "canonical")
s.MakeAssertedSnap(c, otherBase, nil, snap.R(18), "other")
s.MakeAssertedSnap(c, snapReqCore16Base, nil, snap.R(16), "other")
s.MakeAssertedSnap(c, requiredSnap1, nil, snap.R(3), "other")
s.AssertedSnapInfo("required-snap1").LegacyEditedContact = "mailto:[email protected]"
s.MakeAssertedSnap(c, requiredSnap18, nil, snap.R(6), "other")
s.AssertedSnapInfo("required-snap18").LegacyEditedContact = "mailto:[email protected]"
s.MakeAssertedSnap(c, defaultTrackSnap18, nil, snap.R(5), "other")
s.MakeAssertedSnap(c, snapReqOtherBase, nil, snap.R(5), "other")
s.MakeAssertedSnap(c, snapReqContentProvider, nil, snap.R(5), "other")
s.MakeAssertedSnap(c, snapBaseNone, nil, snap.R(1), "other")
}
func (s *imageSuite) loadSeed(c *C, seeddir string) (essSnaps []*seed.Snap, runSnaps []*seed.Snap, roDB asserts.RODatabase) {
label := ""
systems, err := filepath.Glob(filepath.Join(seeddir, "systems", "*"))
c.Assert(err, IsNil)
if len(systems) > 1 {
c.Fatal("expected at most 1 Core 20 recovery system")
} else if len(systems) == 1 {
label = filepath.Base(systems[0])
}
sd, err := seed.Open(seeddir, label)
c.Assert(err, IsNil)
db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
Backstore: asserts.NewMemoryBackstore(),
Trusted: s.StoreSigning.Trusted,
})
c.Assert(err, IsNil)
commitTo := func(b *asserts.Batch) error {
return b.CommitTo(db, nil)
}
err = sd.LoadAssertions(db, commitTo)
c.Assert(err, IsNil)
err = sd.LoadMeta(seed.AllModes, nil, timings.New(nil))
c.Assert(err, IsNil)
essSnaps = sd.EssentialSnaps()
runSnaps, err = sd.ModeSnaps("run")
c.Assert(err, IsNil)
return essSnaps, runSnaps, db
}
func (s *imageSuite) TestSetupSeed(c *C) {
restore := image.MockTrusted(s.StoreSigning.Trusted)
defer restore()
preparedir := c.MkDir()
rootdir := filepath.Join(preparedir, "image")
blobdir := filepath.Join(rootdir, "var/lib/snapd/snaps")
s.setupSnaps(c, map[string]string{
"pc": "canonical",
"pc-kernel": "canonical",
}, "")
gadgetWriteResolvedContentCalled := 0
restore = image.MockWriteResolvedContent(func(prepareImageDir string, info *gadget.Info, gadgetRoot, kernelRoot string) error {
c.Check(prepareImageDir, Equals, preparedir)
c.Check(gadgetRoot, Equals, filepath.Join(preparedir, "gadget"))
c.Check(kernelRoot, Equals, filepath.Join(preparedir, "kernel"))
gadgetWriteResolvedContentCalled++
return nil
})
defer restore()
opts := &image.Options{
PrepareDir: preparedir,
Customizations: image.Customizations{
Validation: "ignore",
},
}
err := image.SetupSeed(s.tsto, s.model, opts)
c.Assert(err, IsNil)
// check seed
seeddir := filepath.Join(rootdir, "var/lib/snapd/seed")
seedsnapsdir := filepath.Join(seeddir, "snaps")
essSnaps, runSnaps, roDB := s.loadSeed(c, seeddir)
c.Check(essSnaps, HasLen, 3)
c.Check(runSnaps, HasLen, 1)
// check the files are in place
for i, name := range []string{"core", "pc-kernel", "pc"} {
info := s.AssertedSnapInfo(name)
fn := info.Filename()
p := filepath.Join(seedsnapsdir, fn)
c.Check(p, testutil.FilePresent)
c.Check(essSnaps[i], DeepEquals, &seed.Snap{
Path: p,
SideInfo: &info.SideInfo,
EssentialType: info.Type(),
Essential: true,
Required: true,
Channel: stableChannel,
})
// precondition
if name == "core" {
c.Check(essSnaps[i].SideInfo.SnapID, Equals, s.AssertedSnapID("core"))
}
}
c.Check(runSnaps[0], DeepEquals, &seed.Snap{
Path: filepath.Join(seedsnapsdir, s.AssertedSnapInfo("required-snap1").Filename()),
SideInfo: &s.AssertedSnapInfo("required-snap1").SideInfo,
Required: true,
Channel: stableChannel,
})
c.Check(runSnaps[0].Path, testutil.FilePresent)
l, err := ioutil.ReadDir(seedsnapsdir)
c.Assert(err, IsNil)
c.Check(l, HasLen, 4)
// check assertions
model1, err := s.model.Ref().Resolve(roDB.Find)
c.Assert(err, IsNil)
c.Check(model1, DeepEquals, s.model)
storeAccountKey := s.StoreSigning.StoreAccountKey("")
brandPubKey := s.Brands.PublicKey("my-brand")
_, err = roDB.Find(asserts.AccountKeyType, map[string]string{
"public-key-sha3-384": storeAccountKey.PublicKeyID(),
})
c.Check(err, IsNil)
_, err = roDB.Find(asserts.AccountKeyType, map[string]string{
"public-key-sha3-384": brandPubKey.ID(),
})
c.Check(err, IsNil)
// check the bootloader config
m, err := s.bootloader.GetBootVars("snap_kernel", "snap_core", "snap_menuentry")
c.Assert(err, IsNil)
c.Check(m["snap_kernel"], Equals, "pc-kernel_2.snap")
c.Check(m["snap_core"], Equals, "core_3.snap")
c.Check(m["snap_menuentry"], Equals, "my display name")
// check symlinks from snap blob dir
kernelInfo := s.AssertedSnapInfo("pc-kernel")
coreInfo := s.AssertedSnapInfo("core")
kernelBlob := filepath.Join(blobdir, kernelInfo.Filename())
dst, err := os.Readlink(kernelBlob)
c.Assert(err, IsNil)
c.Check(dst, Equals, "../seed/snaps/pc-kernel_2.snap")
c.Check(kernelBlob, testutil.FilePresent)
coreBlob := filepath.Join(blobdir, coreInfo.Filename())
dst, err = os.Readlink(coreBlob)
c.Assert(err, IsNil)
c.Check(dst, Equals, "../seed/snaps/core_3.snap")
c.Check(coreBlob, testutil.FilePresent)
c.Check(s.stderr.String(), Equals, "")
// check the downloads
c.Check(s.storeActionsBunchSizes, DeepEquals, []int{4})
c.Check(s.storeActions[0], DeepEquals, &store.SnapAction{
Action: "download",
InstanceName: "core",
Channel: stableChannel,
Flags: store.SnapActionIgnoreValidation,
})
c.Check(s.storeActions[1], DeepEquals, &store.SnapAction{
Action: "download",
InstanceName: "pc-kernel",
Channel: stableChannel,
Flags: store.SnapActionIgnoreValidation,
})
c.Check(s.storeActions[2], DeepEquals, &store.SnapAction{
Action: "download",
InstanceName: "pc",
Channel: stableChannel,
Flags: store.SnapActionIgnoreValidation,
})
// content was resolved and written for ubuntu-image
c.Check(gadgetWriteResolvedContentCalled, Equals, 1)
}
func (s *imageSuite) TestSetupSeedLocalCoreBrandKernel(c *C) {
restore := image.MockTrusted(s.StoreSigning.Trusted)
defer restore()
rootdir := filepath.Join(c.MkDir(), "image")
s.setupSnaps(c, map[string]string{
"pc": "canonical",
"pc-kernel": "my-brand",
}, "")
coreFn := snaptest.MakeTestSnapWithFiles(c, packageCore, [][]string{{"local", ""}})
requiredSnap1Fn := snaptest.MakeTestSnapWithFiles(c, requiredSnap1, [][]string{{"local", ""}})
opts := &image.Options{
Snaps: []string{
coreFn,
requiredSnap1Fn,
},
PrepareDir: filepath.Dir(rootdir),
Customizations: image.Customizations{
Validation: "ignore",
},
}
err := image.SetupSeed(s.tsto, s.model, opts)
c.Assert(err, IsNil)
// check seed
seeddir := filepath.Join(rootdir, "var/lib/snapd/seed")
seedsnapsdir := filepath.Join(seeddir, "snaps")
essSnaps, runSnaps, roDB := s.loadSeed(c, seeddir)
c.Check(essSnaps, HasLen, 3)
c.Check(runSnaps, HasLen, 1)
// check the files are in place
for i, name := range []string{"core_x1.snap", "pc-kernel", "pc"} {
channel := stableChannel
info := s.AssertedSnapInfo(name)
var pinfo snap.PlaceInfo = info
var sideInfo *snap.SideInfo
var snapType snap.Type
if info == nil {
switch name {
case "core_x1.snap":
pinfo = snap.MinimalPlaceInfo("core", snap.R(-1))
sideInfo = &snap.SideInfo{
RealName: "core",
}
channel = ""
snapType = snap.TypeOS
}
} else {
sideInfo = &info.SideInfo
snapType = info.Type()
}
fn := pinfo.Filename()
p := filepath.Join(seedsnapsdir, fn)
c.Check(p, testutil.FilePresent)
c.Check(essSnaps[i], DeepEquals, &seed.Snap{
Path: p,
SideInfo: sideInfo,
EssentialType: snapType,
Essential: true,
Required: true,
Channel: channel,
})
}
c.Check(runSnaps[0], DeepEquals, &seed.Snap{
Path: filepath.Join(seedsnapsdir, "required-snap1_x1.snap"),
SideInfo: &snap.SideInfo{
RealName: "required-snap1",
},
Required: true,
})
c.Check(runSnaps[0].Path, testutil.FilePresent)
// check assertions
decls, err := roDB.FindMany(asserts.SnapDeclarationType, nil)
c.Assert(err, IsNil)
// nothing for core
c.Check(decls, HasLen, 2)
// check the bootloader config
m, err := s.bootloader.GetBootVars("snap_kernel", "snap_core")
c.Assert(err, IsNil)
c.Check(m["snap_kernel"], Equals, "pc-kernel_2.snap")
c.Assert(err, IsNil)
c.Check(m["snap_core"], Equals, "core_x1.snap")
c.Check(s.stderr.String(), Equals, "WARNING: \"core\", \"required-snap1\" installed from local snaps disconnected from a store cannot be refreshed subsequently!\n")
}
func (s *imageSuite) TestSetupSeedWithWideCohort(c *C) {
restore := image.MockTrusted(s.StoreSigning.Trusted)
defer restore()
rootdir := filepath.Join(c.MkDir(), "image")
s.setupSnaps(c, map[string]string{
"pc": "canonical",
"pc-kernel": "canonical",
}, "")
snapFile := snaptest.MakeTestSnapWithFiles(c, devmodeSnap, nil)
opts := &image.Options{
Snaps: []string{snapFile},
PrepareDir: filepath.Dir(rootdir),
WideCohortKey: "wide-cohort-key",
}
err := image.SetupSeed(s.tsto, s.model, opts)
c.Assert(err, IsNil)
// check the downloads
c.Check(s.storeActionsBunchSizes, DeepEquals, []int{4})
c.Check(s.storeActions[0], DeepEquals, &store.SnapAction{
Action: "download",
InstanceName: "core",
Channel: stableChannel,
CohortKey: "wide-cohort-key",
Flags: store.SnapActionIgnoreValidation,
})
c.Check(s.storeActions[1], DeepEquals, &store.SnapAction{
Action: "download",
InstanceName: "pc-kernel",
Channel: stableChannel,
CohortKey: "wide-cohort-key",
Flags: store.SnapActionIgnoreValidation,
})
c.Check(s.storeActions[2], DeepEquals, &store.SnapAction{
Action: "download",
InstanceName: "pc",
Channel: stableChannel,
CohortKey: "wide-cohort-key",
Flags: store.SnapActionIgnoreValidation,
})
c.Check(s.storeActions[3], DeepEquals, &store.SnapAction{
Action: "download",
InstanceName: "required-snap1",
Channel: stableChannel,
CohortKey: "wide-cohort-key",
Flags: store.SnapActionIgnoreValidation,
})
}
func (s *imageSuite) TestSetupSeedDevmodeSnap(c *C) {
restore := image.MockTrusted(s.StoreSigning.Trusted)
defer restore()
rootdir := filepath.Join(c.MkDir(), "image")
s.setupSnaps(c, map[string]string{
"pc": "canonical",
"pc-kernel": "canonical",
}, "")
snapFile := snaptest.MakeTestSnapWithFiles(c, devmodeSnap, nil)
opts := &image.Options{
Snaps: []string{snapFile},
PrepareDir: filepath.Dir(rootdir),
Channel: "beta",
}
err := image.SetupSeed(s.tsto, s.model, opts)
c.Assert(err, IsNil)
// check seed
seeddir := filepath.Join(rootdir, "var/lib/snapd/seed")
seedsnapsdir := filepath.Join(seeddir, "snaps")
essSnaps, runSnaps, _ := s.loadSeed(c, seeddir)
c.Check(essSnaps, HasLen, 3)
c.Check(runSnaps, HasLen, 2)
for i, name := range []string{"core", "pc-kernel", "pc"} {
info := s.AssertedSnapInfo(name)
c.Check(essSnaps[i], DeepEquals, &seed.Snap{
Path: filepath.Join(seedsnapsdir, info.Filename()),
SideInfo: &info.SideInfo,
EssentialType: info.Type(),
Essential: true,
Required: true,
Channel: "beta",
})
}
c.Check(runSnaps[0], DeepEquals, &seed.Snap{
Path: filepath.Join(seedsnapsdir, "required-snap1_3.snap"),
SideInfo: &s.AssertedSnapInfo("required-snap1").SideInfo,
Required: true,
Channel: "beta",
})
// ensure local snaps are put last in seed.yaml
c.Check(runSnaps[1], DeepEquals, &seed.Snap{
Path: filepath.Join(seedsnapsdir, "devmode-snap_x1.snap"),
SideInfo: &snap.SideInfo{
RealName: "devmode-snap",
},
DevMode: true,
// no channel for unasserted snaps
Channel: "",
})
// check devmode-snap blob
c.Check(runSnaps[1].Path, testutil.FilePresent)
}
func (s *imageSuite) TestSetupSeedImageManifest(c *C) {
// Use almost identical setup as TestSetupSeedDevmodeSnap to
// get each type of snap into the manifest
restore := image.MockTrusted(s.StoreSigning.Trusted)
defer restore()
rootdir := filepath.Join(c.MkDir(), "image")
s.setupSnaps(c, map[string]string{
"pc": "canonical",
"pc-kernel": "canonical",
}, "")
snapFile := snaptest.MakeTestSnapWithFiles(c, devmodeSnap, nil)
seedManifestPath := path.Join(rootdir, "seed.manifest")
opts := &image.Options{
Snaps: []string{snapFile},
PrepareDir: filepath.Dir(rootdir),
SeedManifestPath: seedManifestPath,
Channel: "beta",