-
Notifications
You must be signed in to change notification settings - Fork 601
/
Copy pathmanagers_test.go
6159 lines (5143 loc) · 175 KB
/
managers_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) 2016-2019 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 overlord_test
// test the various managers and their operation together through overlord
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"time"
. "gopkg.in/check.v1"
"gopkg.in/tomb.v2"
"gopkg.in/yaml.v2"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/asserts/assertstest"
"github.com/snapcore/snapd/asserts/sysdb"
"github.com/snapcore/snapd/boot"
"github.com/snapcore/snapd/boot/boottest"
"github.com/snapcore/snapd/bootloader"
"github.com/snapcore/snapd/bootloader/bootloadertest"
"github.com/snapcore/snapd/client"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/gadget"
"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/overlord"
"github.com/snapcore/snapd/overlord/assertstate"
"github.com/snapcore/snapd/overlord/assertstate/assertstatetest"
"github.com/snapcore/snapd/overlord/auth"
"github.com/snapcore/snapd/overlord/configstate/config"
"github.com/snapcore/snapd/overlord/devicestate"
"github.com/snapcore/snapd/overlord/devicestate/devicestatetest"
"github.com/snapcore/snapd/overlord/hookstate"
"github.com/snapcore/snapd/overlord/hookstate/ctlcmd"
"github.com/snapcore/snapd/overlord/ifacestate"
"github.com/snapcore/snapd/overlord/snapshotstate"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/release"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/snapfile"
"github.com/snapcore/snapd/snap/snaptest"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/systemd"
"github.com/snapcore/snapd/testutil"
)
var (
settleTimeout = testutil.HostScaledTimeout(45 * time.Second)
aggressiveSettleTimeout = testutil.HostScaledTimeout(50 * time.Millisecond)
connectRetryTimeout = testutil.HostScaledTimeout(70 * time.Millisecond)
)
type automaticSnapshotCall struct {
InstanceName string
SnapConfig map[string]interface{}
Usernames []string
}
type baseMgrsSuite struct {
testutil.BaseTest
tempdir string
storeSigning *assertstest.StoreStack
brands *assertstest.SigningAccounts
devAcct *asserts.Account
serveIDtoName map[string]string
serveSnapPath map[string]string
serveRevision map[string]string
serveOldPaths map[string][]string
serveOldRevs map[string][]string
hijackServeSnap func(http.ResponseWriter)
checkDeviceAndAuthContext func(store.DeviceAndAuthContext)
expectedSerial string
expectedStore string
sessionMacaroon string
o *overlord.Overlord
failNextDownload string
automaticSnapshots []automaticSnapshotCall
}
var (
_ = Suite(&mgrsSuite{})
_ = Suite(&storeCtxSetupSuite{})
)
var (
brandPrivKey, _ = assertstest.GenerateKey(752)
develPrivKey, _ = assertstest.GenerateKey(752)
deviceKey, _ = assertstest.GenerateKey(752)
)
func verifyLastTasksetIsRerefresh(c *C, tts []*state.TaskSet) {
ts := tts[len(tts)-1]
c.Assert(ts.Tasks(), HasLen, 1)
c.Check(ts.Tasks()[0].Kind(), Equals, "check-rerefresh")
}
func (s *baseMgrsSuite) SetUpTest(c *C) {
s.BaseTest.SetUpTest(c)
s.tempdir = c.MkDir()
dirs.SetRootDir(s.tempdir)
s.AddCleanup(func() { dirs.SetRootDir("") })
// needed for system key generation
s.AddCleanup(osutil.MockMountInfo(""))
err := os.MkdirAll(filepath.Dir(dirs.SnapStateFile), 0755)
c.Assert(err, IsNil)
// needed by hooks
s.AddCleanup(testutil.MockCommand(c, "snap", "").Restore)
restoreCheckFreeSpace := snapstate.MockOsutilCheckFreeSpace(func(string, uint64) error { return nil })
s.AddCleanup(restoreCheckFreeSpace)
oldSetupInstallHook := snapstate.SetupInstallHook
oldSetupRemoveHook := snapstate.SetupRemoveHook
snapstate.SetupRemoveHook = hookstate.SetupRemoveHook
snapstate.SetupInstallHook = hookstate.SetupInstallHook
s.AddCleanup(func() {
snapstate.SetupRemoveHook = oldSetupRemoveHook
snapstate.SetupInstallHook = oldSetupInstallHook
})
s.automaticSnapshots = nil
r := snapshotstate.MockBackendSave(func(_ context.Context, id uint64, si *snap.Info, cfg map[string]interface{}, usernames []string) (*client.Snapshot, error) {
s.automaticSnapshots = append(s.automaticSnapshots, automaticSnapshotCall{InstanceName: si.InstanceName(), SnapConfig: cfg, Usernames: usernames})
return nil, nil
})
s.AddCleanup(r)
s.AddCleanup(ifacestate.MockConnectRetryTimeout(connectRetryTimeout))
os.Setenv("SNAPPY_SQUASHFS_UNPACK_FOR_TESTS", "1")
s.AddCleanup(func() { os.Unsetenv("SNAPPY_SQUASHFS_UNPACK_FOR_TESTS") })
// create a fake systemd environment
os.MkdirAll(filepath.Join(dirs.SnapServicesDir, "multi-user.target.wants"), 0755)
r = systemd.MockSystemctl(func(cmd ...string) ([]byte, error) {
return []byte("ActiveState=inactive\n"), nil
})
s.AddCleanup(r)
s.storeSigning = assertstest.NewStoreStack("can0nical", nil)
s.brands = assertstest.NewSigningAccounts(s.storeSigning)
s.brands.Register("my-brand", brandPrivKey, map[string]interface{}{
"validation": "verified",
})
s.AddCleanup(sysdb.InjectTrusted(s.storeSigning.Trusted))
s.devAcct = assertstest.NewAccount(s.storeSigning, "devdevdev", map[string]interface{}{
"account-id": "devdevdev",
}, "")
err = s.storeSigning.Add(s.devAcct)
c.Assert(err, IsNil)
s.serveIDtoName = make(map[string]string)
s.serveSnapPath = make(map[string]string)
s.serveRevision = make(map[string]string)
s.serveOldPaths = make(map[string][]string)
s.serveOldRevs = make(map[string][]string)
s.hijackServeSnap = nil
s.checkDeviceAndAuthContext = nil
s.expectedSerial = ""
s.expectedStore = ""
s.sessionMacaroon = ""
s.AddCleanup(ifacestate.MockSecurityBackends(nil))
o, err := overlord.New(nil)
c.Assert(err, IsNil)
err = o.StartUp()
c.Assert(err, IsNil)
o.InterfaceManager().DisableUDevMonitor()
s.o = o
st := s.o.State()
st.Lock()
defer st.Unlock()
st.Set("seeded", true)
// registered
err = assertstate.Add(st, sysdb.GenericClassicModel())
c.Assert(err, IsNil)
devicestatetest.SetDevice(st, &auth.DeviceState{
Brand: "generic",
Model: "generic-classic",
Serial: "serialserial",
})
// add "core" snap declaration
headers := map[string]interface{}{
"series": "16",
"snap-name": "core",
"publisher-id": "can0nical",
"timestamp": time.Now().Format(time.RFC3339),
}
headers["snap-id"] = fakeSnapID(headers["snap-name"].(string))
err = assertstate.Add(st, s.storeSigning.StoreAccountKey(""))
c.Assert(err, IsNil)
a, err := s.storeSigning.Sign(asserts.SnapDeclarationType, headers, nil, "")
c.Assert(err, IsNil)
err = assertstate.Add(st, a)
c.Assert(err, IsNil)
s.serveRevision["core"] = "1"
s.serveIDtoName[fakeSnapID("core")] = "core"
err = s.storeSigning.Add(a)
c.Assert(err, IsNil)
// add "snap1" snap declaration
headers = map[string]interface{}{
"series": "16",
"snap-name": "snap1",
"publisher-id": "can0nical",
"timestamp": time.Now().Format(time.RFC3339),
}
headers["snap-id"] = fakeSnapID(headers["snap-name"].(string))
a2, err := s.storeSigning.Sign(asserts.SnapDeclarationType, headers, nil, "")
c.Assert(err, IsNil)
c.Assert(assertstate.Add(st, a2), IsNil)
c.Assert(s.storeSigning.Add(a2), IsNil)
// add "snap2" snap declaration
headers = map[string]interface{}{
"series": "16",
"snap-name": "snap2",
"publisher-id": "can0nical",
"timestamp": time.Now().Format(time.RFC3339),
}
headers["snap-id"] = fakeSnapID(headers["snap-name"].(string))
a3, err := s.storeSigning.Sign(asserts.SnapDeclarationType, headers, nil, "")
c.Assert(err, IsNil)
c.Assert(assertstate.Add(st, a3), IsNil)
c.Assert(s.storeSigning.Add(a3), IsNil)
// add "some-snap" snap declaration
headers = map[string]interface{}{
"series": "16",
"snap-name": "some-snap",
"publisher-id": "can0nical",
"timestamp": time.Now().Format(time.RFC3339),
}
headers["snap-id"] = fakeSnapID(headers["snap-name"].(string))
a4, err := s.storeSigning.Sign(asserts.SnapDeclarationType, headers, nil, "")
c.Assert(err, IsNil)
c.Assert(assertstate.Add(st, a4), IsNil)
c.Assert(s.storeSigning.Add(a4), IsNil)
// add "other-snap" snap declaration
headers = map[string]interface{}{
"series": "16",
"snap-name": "other-snap",
"publisher-id": "can0nical",
"timestamp": time.Now().Format(time.RFC3339),
}
headers["snap-id"] = fakeSnapID(headers["snap-name"].(string))
a5, err := s.storeSigning.Sign(asserts.SnapDeclarationType, headers, nil, "")
c.Assert(err, IsNil)
c.Assert(assertstate.Add(st, a5), IsNil)
c.Assert(s.storeSigning.Add(a5), IsNil)
// add pc-kernel snap declaration
headers = map[string]interface{}{
"series": "16",
"snap-name": "pc-kernel",
"publisher-id": "can0nical",
"timestamp": time.Now().Format(time.RFC3339),
}
headers["snap-id"] = fakeSnapID(headers["snap-name"].(string))
a6, err := s.storeSigning.Sign(asserts.SnapDeclarationType, headers, nil, "")
c.Assert(err, IsNil)
c.Assert(assertstate.Add(st, a6), IsNil)
c.Assert(s.storeSigning.Add(a6), IsNil)
// add pc snap declaration
headers = map[string]interface{}{
"series": "16",
"snap-name": "pc",
"publisher-id": "can0nical",
"timestamp": time.Now().Format(time.RFC3339),
}
headers["snap-id"] = fakeSnapID(headers["snap-name"].(string))
a7, err := s.storeSigning.Sign(asserts.SnapDeclarationType, headers, nil, "")
c.Assert(err, IsNil)
c.Assert(assertstate.Add(st, a7), IsNil)
c.Assert(s.storeSigning.Add(a7), IsNil)
// add core itself
snapstate.Set(st, "core", &snapstate.SnapState{
Active: true,
Sequence: []*snap.SideInfo{
{RealName: "core", SnapID: fakeSnapID("core"), Revision: snap.R(1)},
},
Current: snap.R(1),
SnapType: "os",
Flags: snapstate.Flags{
Required: true,
},
})
// don't actually try to talk to the store on snapstate.Ensure
// needs doing after the call to devicestate.Manager (which happens in overlord.New)
snapstate.CanAutoRefresh = nil
st.Set("refresh-privacy-key", "privacy-key")
// For triggering errors
erroringHandler := func(task *state.Task, _ *tomb.Tomb) error {
return errors.New("error out")
}
s.o.TaskRunner().AddHandler("error-trigger", erroringHandler, nil)
// setup cloud-init as restricted so that tests by default don't run the
// full EnsureCloudInitRestricted logic in the devicestate mgr
snapdCloudInitRestrictedFile := filepath.Join(dirs.GlobalRootDir, "etc/cloud/cloud.cfg.d/zzzz_snapd.cfg")
err = os.MkdirAll(filepath.Dir(snapdCloudInitRestrictedFile), 0755)
c.Assert(err, IsNil)
err = ioutil.WriteFile(snapdCloudInitRestrictedFile, nil, 0644)
c.Assert(err, IsNil)
}
type mgrsSuite struct {
baseMgrsSuite
}
func makeTestSnapWithFiles(c *C, snapYamlContent string, files [][]string) string {
info, err := snap.InfoFromSnapYaml([]byte(snapYamlContent))
c.Assert(err, IsNil)
for _, app := range info.Apps {
// files is a list of (filename, content)
files = append(files, []string{app.Command, ""})
}
return snaptest.MakeTestSnapWithFiles(c, snapYamlContent, files)
}
func makeTestSnap(c *C, snapYamlContent string) string {
return makeTestSnapWithFiles(c, snapYamlContent, nil)
}
func (s *mgrsSuite) TestHappyLocalInstall(c *C) {
snapYamlContent := `name: foo
apps:
bar:
command: bin/bar
`
snapPath := makeTestSnap(c, snapYamlContent+"version: 1.0")
st := s.o.State()
st.Lock()
defer st.Unlock()
ts, _, err := snapstate.InstallPath(st, &snap.SideInfo{RealName: "foo"}, snapPath, "", "", snapstate.Flags{DevMode: true})
c.Assert(err, IsNil)
chg := st.NewChange("install-snap", "...")
chg.AddAll(ts)
st.Unlock()
err = s.o.Settle(settleTimeout)
st.Lock()
c.Assert(err, IsNil)
c.Assert(chg.Status(), Equals, state.DoneStatus, Commentf("install-snap change failed with: %v", chg.Err()))
snap, err := snapstate.CurrentInfo(st, "foo")
c.Assert(err, IsNil)
// ensure that the binary wrapper file got generated with the right
// name
binaryWrapper := filepath.Join(dirs.SnapBinariesDir, "foo.bar")
c.Assert(osutil.IsSymlink(binaryWrapper), Equals, true)
// data dirs
c.Assert(osutil.IsDirectory(snap.DataDir()), Equals, true)
c.Assert(osutil.IsDirectory(snap.CommonDataDir()), Equals, true)
// snap file and its mounting
// after install the snap file is in the right dir
c.Assert(osutil.FileExists(filepath.Join(dirs.SnapBlobDir, "foo_x1.snap")), Equals, true)
// ensure the right unit is created
mup := systemd.MountUnitPath(filepath.Join(dirs.StripRootDir(dirs.SnapMountDir), "foo/x1"))
c.Assert(mup, testutil.FileMatches, fmt.Sprintf("(?ms).*^Where=%s/foo/x1", dirs.StripRootDir(dirs.SnapMountDir)))
c.Assert(mup, testutil.FileMatches, "(?ms).*^What=/var/lib/snapd/snaps/foo_x1.snap")
}
func (s *mgrsSuite) TestLocalInstallUndo(c *C) {
snapYamlContent := `name: foo
apps:
bar:
command: bin/bar
hooks:
install:
configure:
`
snapPath := makeTestSnap(c, snapYamlContent+"version: 1.0")
installHook := false
defer hookstate.MockRunHook(func(ctx *hookstate.Context, _ *tomb.Tomb) ([]byte, error) {
switch ctx.HookName() {
case "install":
installHook = true
_, _, err := ctlcmd.Run(ctx, []string{"set", "installed=true"}, 0)
c.Assert(err, IsNil)
return nil, nil
case "configure":
return nil, errors.New("configure failed")
}
return nil, nil
})()
st := s.o.State()
st.Lock()
defer st.Unlock()
ts, _, err := snapstate.InstallPath(st, &snap.SideInfo{RealName: "foo"}, snapPath, "", "", snapstate.Flags{DevMode: true})
c.Assert(err, IsNil)
chg := st.NewChange("install-snap", "...")
chg.AddAll(ts)
st.Unlock()
err = s.o.Settle(settleTimeout)
st.Lock()
c.Assert(err, IsNil)
c.Assert(chg.Status(), Equals, state.ErrorStatus, Commentf("install-snap unexpectedly succeeded"))
// check undo statutes
for _, t := range chg.Tasks() {
which := t.Kind()
expectedStatus := state.UndoneStatus
switch t.Kind() {
case "prerequisites":
expectedStatus = state.DoneStatus
case "run-hook":
var hs hookstate.HookSetup
err := t.Get("hook-setup", &hs)
c.Assert(err, IsNil)
switch hs.Hook {
case "install":
expectedStatus = state.UndoneStatus
case "configure":
expectedStatus = state.ErrorStatus
case "check-health":
expectedStatus = state.HoldStatus
}
which += fmt.Sprintf("[%s]", hs.Hook)
}
c.Assert(t.Status(), Equals, expectedStatus, Commentf("%s", which))
}
// install hooks was called
c.Check(installHook, Equals, true)
// nothing in snaps
all, err := snapstate.All(st)
c.Assert(err, IsNil)
c.Check(all, HasLen, 1)
_, ok := all["core"]
c.Check(ok, Equals, true)
// nothing in config
var config map[string]*json.RawMessage
err = st.Get("config", &config)
c.Assert(err, IsNil)
c.Check(config, HasLen, 1)
_, ok = config["core"]
c.Check(ok, Equals, true)
snapdirs, err := filepath.Glob(filepath.Join(dirs.SnapMountDir, "*"))
c.Assert(err, IsNil)
// just README and bin
c.Check(snapdirs, HasLen, 2)
for _, d := range snapdirs {
c.Check(filepath.Base(d), Not(Equals), "foo")
}
}
func (s *mgrsSuite) TestHappyRemove(c *C) {
oldEstimateSnapshotSize := snapstate.EstimateSnapshotSize
snapstate.EstimateSnapshotSize = func(st *state.State, instanceName string, users []string) (uint64, error) {
return 0, nil
}
defer func() {
snapstate.EstimateSnapshotSize = oldEstimateSnapshotSize
}()
st := s.o.State()
st.Lock()
defer st.Unlock()
snapYamlContent := `name: foo
apps:
bar:
command: bin/bar
`
snapInfo := s.installLocalTestSnap(c, snapYamlContent+"version: 1.0")
// set config
tr := config.NewTransaction(st)
c.Assert(tr.Set("foo", "key", "value"), IsNil)
tr.Commit()
ts, err := snapstate.Remove(st, "foo", snap.R(0), nil)
c.Assert(err, IsNil)
chg := st.NewChange("remove-snap", "...")
chg.AddAll(ts)
st.Unlock()
err = s.o.Settle(settleTimeout)
st.Lock()
c.Assert(err, IsNil)
c.Assert(chg.Status(), Equals, state.DoneStatus, Commentf("remove-snap change failed with: %v", chg.Err()))
// ensure that the binary wrapper file got removed
binaryWrapper := filepath.Join(dirs.SnapBinariesDir, "foo.bar")
c.Assert(osutil.FileExists(binaryWrapper), Equals, false)
// data dirs
c.Assert(osutil.FileExists(snapInfo.DataDir()), Equals, false)
c.Assert(osutil.FileExists(snapInfo.CommonDataDir()), Equals, false)
// snap file and its mount
c.Assert(osutil.FileExists(filepath.Join(dirs.SnapBlobDir, "foo_x1.snap")), Equals, false)
mup := systemd.MountUnitPath(filepath.Join(dirs.StripRootDir(dirs.SnapMountDir), "foo/x1"))
c.Assert(osutil.FileExists(mup), Equals, false)
// automatic snapshot was created
c.Assert(s.automaticSnapshots, DeepEquals, []automaticSnapshotCall{{"foo", map[string]interface{}{"key": "value"}, nil}})
}
func fakeSnapID(name string) string {
const suffix = "idididididididididididididididid"
return name + suffix[len(name)+1:]
}
const (
snapV2 = `{
"architectures": [
"all"
],
"download": {
"url": "@URL@",
"size": 123
},
"epoch": @EPOCH@,
"type": "@TYPE@",
"name": "@NAME@",
"revision": @REVISION@,
"snap-id": "@SNAPID@",
"summary": "Foo",
"description": "this is a description",
"version": "@VERSION@",
"publisher": {
"id": "devdevdev",
"name": "bar"
},
"media": [
{"type": "icon", "url": "@ICON@"}
]
}`
)
var fooSnapID = fakeSnapID("foo")
func (s *baseMgrsSuite) prereqSnapAssertions(c *C, extraHeaders ...map[string]interface{}) *asserts.SnapDeclaration {
if len(extraHeaders) == 0 {
extraHeaders = []map[string]interface{}{{}}
}
var snapDecl *asserts.SnapDeclaration
for _, extraHeaders := range extraHeaders {
headers := map[string]interface{}{
"series": "16",
"snap-name": "foo",
"publisher-id": "devdevdev",
"timestamp": time.Now().Format(time.RFC3339),
}
for h, v := range extraHeaders {
headers[h] = v
}
headers["snap-id"] = fakeSnapID(headers["snap-name"].(string))
a, err := s.storeSigning.Sign(asserts.SnapDeclarationType, headers, nil, "")
c.Assert(err, IsNil)
err = s.storeSigning.Add(a)
c.Assert(err, IsNil)
snapDecl = a.(*asserts.SnapDeclaration)
}
return snapDecl
}
func (s *baseMgrsSuite) makeStoreTestSnapWithFiles(c *C, snapYaml string, revno string, files [][]string) (path, digest string) {
info, err := snap.InfoFromSnapYaml([]byte(snapYaml))
c.Assert(err, IsNil)
snapPath := makeTestSnapWithFiles(c, snapYaml, files)
snapDigest, size, err := asserts.SnapFileSHA3_384(snapPath)
c.Assert(err, IsNil)
headers := map[string]interface{}{
"snap-id": fakeSnapID(info.SnapName()),
"snap-sha3-384": snapDigest,
"snap-size": fmt.Sprintf("%d", size),
"snap-revision": revno,
"developer-id": "devdevdev",
"timestamp": time.Now().Format(time.RFC3339),
}
snapRev, err := s.storeSigning.Sign(asserts.SnapRevisionType, headers, nil, "")
c.Assert(err, IsNil)
err = s.storeSigning.Add(snapRev)
c.Assert(err, IsNil)
return snapPath, snapDigest
}
func (s *baseMgrsSuite) makeStoreTestSnap(c *C, snapYaml string, revno string) (path, digest string) {
return s.makeStoreTestSnapWithFiles(c, snapYaml, revno, nil)
}
func (s *baseMgrsSuite) pathFor(name, revno string) string {
if revno == s.serveRevision[name] {
return s.serveSnapPath[name]
}
for i, r := range s.serveOldRevs[name] {
if r == revno {
return s.serveOldPaths[name][i]
}
}
return "/not/found"
}
func (s *baseMgrsSuite) newestThatCanRead(name string, epoch snap.Epoch) (info *snap.Info, rev string) {
if s.serveSnapPath[name] == "" {
return nil, ""
}
idx := len(s.serveOldPaths[name])
rev = s.serveRevision[name]
path := s.serveSnapPath[name]
for {
snapf, err := snapfile.Open(path)
if err != nil {
panic(err)
}
info, err := snap.ReadInfoFromSnapFile(snapf, nil)
if err != nil {
panic(err)
}
if info.Epoch.CanRead(epoch) {
return info, rev
}
idx--
if idx < 0 {
return nil, ""
}
path = s.serveOldPaths[name][idx]
rev = s.serveOldRevs[name][idx]
}
}
func (s *baseMgrsSuite) mockStore(c *C) *httptest.Server {
var baseURL *url.URL
fillHit := func(hitTemplate, revno string, info *snap.Info) string {
epochBuf, err := json.Marshal(info.Epoch)
if err != nil {
panic(err)
}
name := info.SnapName()
hit := strings.Replace(hitTemplate, "@URL@", baseURL.String()+"/api/v1/snaps/download/"+name+"/"+revno, -1)
hit = strings.Replace(hit, "@NAME@", name, -1)
hit = strings.Replace(hit, "@SNAPID@", fakeSnapID(name), -1)
hit = strings.Replace(hit, "@ICON@", baseURL.String()+"/icon", -1)
hit = strings.Replace(hit, "@VERSION@", info.Version, -1)
hit = strings.Replace(hit, "@REVISION@", revno, -1)
hit = strings.Replace(hit, `@TYPE@`, string(info.Type()), -1)
hit = strings.Replace(hit, `@EPOCH@`, string(epochBuf), -1)
return hit
}
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// all URLS are /api/v1/snaps/... or /v2/snaps/ or /v2/assertions/... so
// check the url is sane and discard the common prefix
// to simplify indexing into the comps slice.
comps := strings.Split(r.URL.Path, "/")
if len(comps) < 2 {
panic("unexpected url path: " + r.URL.Path)
}
if comps[1] == "api" { //v1
if len(comps) <= 4 {
panic("unexpected url path: " + r.URL.Path)
}
comps = comps[4:]
if comps[0] == "auth" {
comps[0] = "auth:" + comps[1]
}
} else { // v2
if len(comps) <= 3 {
panic("unexpected url path: " + r.URL.Path)
}
if comps[2] == "assertions" {
// preserve "assertions" component
comps = comps[2:]
} else {
// drop common "snap" component
comps = comps[3:]
}
comps[0] = "v2:" + comps[0]
}
switch comps[0] {
case "auth:nonces":
w.Write([]byte(`{"nonce": "NONCE"}`))
return
case "auth:sessions":
// quick sanity check
reqBody, err := ioutil.ReadAll(r.Body)
c.Check(err, IsNil)
c.Check(bytes.Contains(reqBody, []byte("nonce: NONCE")), Equals, true)
c.Check(bytes.Contains(reqBody, []byte(fmt.Sprintf("serial: %s", s.expectedSerial))), Equals, true)
c.Check(bytes.Contains(reqBody, []byte(fmt.Sprintf("store: %s", s.expectedStore))), Equals, true)
c.Check(s.sessionMacaroon, Not(Equals), "")
w.WriteHeader(200)
w.Write([]byte(fmt.Sprintf(`{"macaroon": "%s"}`, s.sessionMacaroon)))
return
case "v2:assertions":
ref := &asserts.Ref{
Type: asserts.Type(comps[1]),
PrimaryKey: comps[2:],
}
a, err := ref.Resolve(s.storeSigning.Find)
if asserts.IsNotFound(err) {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
w.Write([]byte(`{"error-list":[{"code":"not-found","message":"..."}]}`))
return
}
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", asserts.MediaType)
w.WriteHeader(200)
w.Write(asserts.Encode(a))
return
case "download":
if s.sessionMacaroon != "" {
// FIXME: download is still using the old headers!
c.Check(r.Header.Get("X-Device-Authorization"), Equals, fmt.Sprintf(`Macaroon root="%s"`, s.sessionMacaroon))
}
if s.failNextDownload == comps[1] {
s.failNextDownload = ""
w.WriteHeader(418)
return
}
if s.hijackServeSnap != nil {
s.hijackServeSnap(w)
return
}
snapR, err := os.Open(s.pathFor(comps[1], comps[2]))
if err != nil {
panic(err)
}
io.Copy(w, snapR)
case "v2:refresh":
if s.sessionMacaroon != "" {
c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, fmt.Sprintf(`Macaroon root="%s"`, s.sessionMacaroon))
}
dec := json.NewDecoder(r.Body)
var input struct {
Actions []struct {
Action string `json:"action"`
SnapID string `json:"snap-id"`
Name string `json:"name"`
InstanceKey string `json:"instance-key"`
Epoch snap.Epoch `json:"epoch"`
// assertions
Key string `json:"key"`
Assertions []struct {
Type string `json:"type"`
PrimaryKey []string `json:"primary-key"`
IfNewerThan *int `json:"if-newer-than"`
}
} `json:"actions"`
Context []struct {
SnapID string `json:"snap-id"`
Epoch snap.Epoch `json:"epoch"`
} `json:"context"`
}
if err := dec.Decode(&input); err != nil {
panic(err)
}
id2epoch := make(map[string]snap.Epoch, len(input.Context))
for _, s := range input.Context {
id2epoch[s.SnapID] = s.Epoch
}
type resultJSON struct {
Result string `json:"result"`
SnapID string `json:"snap-id"`
Name string `json:"name"`
Snap json.RawMessage `json:"snap"`
InstanceKey string `json:"instance-key"`
// For assertions
Key string `json:"key"`
AssertionURLs []string `json:"assertion-stream-urls"`
}
var results []resultJSON
for _, a := range input.Actions {
if a.Action == "fetch-assertions" {
urls := []string{}
for _, ar := range a.Assertions {
ref := &asserts.Ref{
Type: asserts.Type(ar.Type),
PrimaryKey: ar.PrimaryKey,
}
_, err := ref.Resolve(s.storeSigning.Find)
if err != nil {
panic("missing assertions not supported")
}
urls = append(urls, fmt.Sprintf("%s/v2/assertions/%s", baseURL.String(), ref.Unique()))
}
results = append(results, resultJSON{
Result: "fetch-assertions",
Key: a.Key,
AssertionURLs: urls,
})
continue
}
name := s.serveIDtoName[a.SnapID]
epoch := id2epoch[a.SnapID]
if a.Action == "install" {
name = a.Name
epoch = a.Epoch
}
info, revno := s.newestThatCanRead(name, epoch)
if info == nil {
// no match
continue
}
results = append(results, resultJSON{
Result: a.Action,
SnapID: a.SnapID,
InstanceKey: a.InstanceKey,
Name: name,
Snap: json.RawMessage(fillHit(snapV2, revno, info)),
})
}
w.WriteHeader(200)
output, err := json.Marshal(map[string]interface{}{
"results": results,
})
if err != nil {
panic(err)
}
w.Write(output)
default:
panic("unexpected url path: " + r.URL.Path)
}
}))
c.Assert(mockServer, NotNil)
baseURL, _ = url.Parse(mockServer.URL)
storeCfg := store.Config{
StoreBaseURL: baseURL,
}
mStore := store.New(&storeCfg, nil)
st := s.o.State()
st.Lock()
snapstate.ReplaceStore(s.o.State(), mStore)
st.Unlock()
// this will be used by remodeling cases
storeNew := func(cfg *store.Config, dac store.DeviceAndAuthContext) *store.Store {
cfg.StoreBaseURL = baseURL
if s.checkDeviceAndAuthContext != nil {
s.checkDeviceAndAuthContext(dac)
}
return store.New(cfg, dac)
}
s.AddCleanup(overlord.MockStoreNew(storeNew))
return mockServer
}
// serveSnap starts serving the snap at snapPath, moving the current
// one onto the list of previous ones if already set.
func (s *baseMgrsSuite) serveSnap(snapPath, revno string) {
snapf, err := snapfile.Open(snapPath)
if err != nil {
panic(err)
}
info, err := snap.ReadInfoFromSnapFile(snapf, nil)
if err != nil {
panic(err)
}
name := info.SnapName()
s.serveIDtoName[fakeSnapID(name)] = name
if oldPath := s.serveSnapPath[name]; oldPath != "" {
oldRev := s.serveRevision[name]
if oldRev == "" {
panic("old path set but not old revision")
}
s.serveOldPaths[name] = append(s.serveOldPaths[name], oldPath)
s.serveOldRevs[name] = append(s.serveOldRevs[name], oldRev)
}
s.serveSnapPath[name] = snapPath
s.serveRevision[name] = revno
}
func (s *mgrsSuite) TestHappyRemoteInstallAndUpgradeSvc(c *C) {
// test install through store and update, plus some mechanics
// of update
// TODO: ok to split if it gets too messy to maintain
s.prereqSnapAssertions(c)
snapYamlContent := `name: foo
version: @VERSION@
apps:
bar:
command: bin/bar
svc:
command: svc
daemon: forking
`
ver := "1.0"
revno := "42"
snapPath, digest := s.makeStoreTestSnap(c, strings.Replace(snapYamlContent, "@VERSION@", ver, -1), revno)
s.serveSnap(snapPath, revno)
mockServer := s.mockStore(c)
defer mockServer.Close()
st := s.o.State()
st.Lock()
defer st.Unlock()
ts, err := snapstate.Install(context.TODO(), st, "foo", nil, 0, snapstate.Flags{})
c.Assert(err, IsNil)
chg := st.NewChange("install-snap", "...")
chg.AddAll(ts)
st.Unlock()
err = s.o.Settle(settleTimeout)
st.Lock()
c.Assert(err, IsNil)
c.Assert(chg.Status(), Equals, state.DoneStatus, Commentf("install-snap change failed with: %v", chg.Err()))