/
snapstate.go
3088 lines (2702 loc) · 94.1 KB
/
snapstate.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-2021 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 snapstate implements the manager and state aspects responsible for the installation and removal of snaps.
package snapstate
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"sort"
"strings"
"time"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/boot"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/features"
"github.com/snapcore/snapd/gadget"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/overlord/auth"
"github.com/snapcore/snapd/overlord/configstate/config"
"github.com/snapcore/snapd/overlord/ifacestate/ifacerepo"
"github.com/snapcore/snapd/overlord/snapstate/backend"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/release"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/channel"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/strutil"
)
// control flags for doInstall
const (
skipConfigure = 1 << iota
)
// control flags for "Configure()"
const (
IgnoreHookError = 1 << iota
TrackHookError
UseConfigDefaults
)
const (
DownloadAndChecksDoneEdge = state.TaskSetEdge("download-and-checks-done")
BeginEdge = state.TaskSetEdge("begin")
BeforeHooksEdge = state.TaskSetEdge("before-hooks")
HooksEdge = state.TaskSetEdge("hooks")
)
var ErrNothingToDo = errors.New("nothing to do")
var osutilCheckFreeSpace = osutil.CheckFreeSpace
// TestingLeaveOutKernelUpdateGadgetAssets can be used to simulate an upgrade
// from a broken snapd that does not generate a "update-gadget-assets" task.
// See LP:#1940553
var TestingLeaveOutKernelUpdateGadgetAssets bool = false
type minimalInstallInfo interface {
InstanceName() string
Type() snap.Type
SnapBase() string
DownloadSize() int64
Prereq(st *state.State) []string
}
type updateParamsFunc func(*snap.Info) (*RevisionOptions, Flags, *SnapState)
type readyUpdateInfo interface {
minimalInstallInfo
SnapSetupForUpdate(st *state.State, params updateParamsFunc, userID int, globalFlags *Flags) (*SnapSetup, *SnapState, error)
}
// ByType supports sorting by snap type. The most important types come first.
type byType []minimalInstallInfo
func (r byType) Len() int { return len(r) }
func (r byType) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
func (r byType) Less(i, j int) bool {
return r[i].Type().SortsBefore(r[j].Type())
}
type installSnapInfo struct {
*snap.Info
}
func (ins installSnapInfo) DownloadSize() int64 {
return ins.DownloadInfo.Size
}
// SnapBase returns the base snap of the snap.
func (ins installSnapInfo) SnapBase() string {
return ins.Base
}
func (ins installSnapInfo) Prereq(st *state.State) []string {
return defaultContentPlugProviders(st, ins.Info)
}
func (ins installSnapInfo) SnapSetupForUpdate(st *state.State, params updateParamsFunc, userID int, globalFlags *Flags) (*SnapSetup, *SnapState, error) {
update := ins.Info
revnoOpts, flags, snapst := params(update)
flags.IsAutoRefresh = globalFlags.IsAutoRefresh
flags, err := earlyChecks(st, snapst, update, flags)
if err != nil {
return nil, nil, err
}
snapUserID, err := userIDForSnap(st, snapst, userID)
if err != nil {
return nil, nil, err
}
snapsup := SnapSetup{
Base: update.Base,
Prereq: defaultContentPlugProviders(st, update),
Channel: revnoOpts.Channel,
CohortKey: revnoOpts.CohortKey,
UserID: snapUserID,
Flags: flags.ForSnapSetup(),
DownloadInfo: &update.DownloadInfo,
SideInfo: &update.SideInfo,
Type: update.Type(),
PlugsOnly: len(update.Slots) == 0,
InstanceKey: update.InstanceKey,
auxStoreInfo: auxStoreInfo{
Website: update.Website,
Media: update.Media,
},
}
return &snapsup, snapst, nil
}
// soundness check
var _ readyUpdateInfo = installSnapInfo{}
// InsufficientSpaceError represents an error where there is not enough disk
// space to perform an operation.
type InsufficientSpaceError struct {
// Path is the filesystem path checked for available disk space
Path string
// Snaps affected by the failing operation
Snaps []string
// Kind of the change that failed
ChangeKind string
// Message is optional, otherwise one is composed from the other information
Message string
}
func (e *InsufficientSpaceError) Error() string {
if e.Message != "" {
return e.Message
}
if len(e.Snaps) > 0 {
snaps := strings.Join(e.Snaps, ", ")
return fmt.Sprintf("insufficient space in %q to perform %q change for the following snaps: %s", e.Path, e.ChangeKind, snaps)
}
return fmt.Sprintf("insufficient space in %q", e.Path)
}
// safetyMarginDiskSpace returns size plus a safety margin (5Mb)
func safetyMarginDiskSpace(size uint64) uint64 {
return size + 5*1024*1024
}
func isParallelInstallable(snapsup *SnapSetup) error {
if snapsup.InstanceKey == "" {
return nil
}
if snapsup.Type == snap.TypeApp {
return nil
}
return fmt.Errorf("cannot install snap of type %v as %q", snapsup.Type, snapsup.InstanceName())
}
func optedIntoSnapdSnap(st *state.State) (bool, error) {
tr := config.NewTransaction(st)
experimentalAllowSnapd, err := features.Flag(tr, features.SnapdSnap)
if err != nil && !config.IsNoOption(err) {
return false, err
}
return experimentalAllowSnapd, nil
}
func doInstall(st *state.State, snapst *SnapState, snapsup *SnapSetup, flags int, fromChange string, inUseCheck func(snap.Type) (boot.InUseFunc, error)) (*state.TaskSet, error) {
// NB: we should strive not to need or propagate deviceCtx
// here, the resulting effects/changes were not pleasant at
// one point
tr := config.NewTransaction(st)
experimentalRefreshAppAwareness, err := features.Flag(tr, features.RefreshAppAwareness)
if err != nil && !config.IsNoOption(err) {
return nil, err
}
experimentalGateAutoRefreshHook, err := features.Flag(tr, features.GateAutoRefreshHook)
if err != nil && !config.IsNoOption(err) {
return nil, err
}
if snapsup.InstanceName() == "system" {
return nil, fmt.Errorf("cannot install reserved snap name 'system'")
}
if snapst.IsInstalled() && !snapst.Active {
return nil, fmt.Errorf("cannot update disabled snap %q", snapsup.InstanceName())
}
if snapst.IsInstalled() && !snapsup.Flags.Revert {
if inUseCheck == nil {
return nil, fmt.Errorf("internal error: doInstall: inUseCheck not provided for refresh")
}
}
if snapsup.Flags.Classic {
if !release.OnClassic {
return nil, fmt.Errorf("classic confinement is only supported on classic systems")
} else if !dirs.SupportsClassicConfinement() {
return nil, fmt.Errorf(i18n.G("classic confinement requires snaps under /snap or symlink from /snap to %s"), dirs.SnapMountDir)
}
}
if !snapst.IsInstalled() { // install?
// check that the snap command namespace doesn't conflict with an enabled alias
if err := checkSnapAliasConflict(st, snapsup.InstanceName()); err != nil {
return nil, err
}
}
if err := isParallelInstallable(snapsup); err != nil {
return nil, err
}
if err := checkChangeConflictIgnoringOneChange(st, snapsup.InstanceName(), snapst, fromChange); err != nil {
return nil, err
}
if snapst.IsInstalled() {
// consider also the current revision to set plugs-only hint
info, err := snapst.CurrentInfo()
if err != nil {
return nil, err
}
snapsup.PlugsOnly = snapsup.PlugsOnly && (len(info.Slots) == 0)
if experimentalRefreshAppAwareness && !snapsup.Flags.IgnoreRunning {
// Note that because we are modifying the snap state inside
// softCheckNothingRunningForRefresh, this block must be located
// after the conflict check done above.
if err := softCheckNothingRunningForRefresh(st, snapst, info); err != nil {
return nil, err
}
}
if experimentalGateAutoRefreshHook {
// If this snap was held, then remove it from snaps-hold.
if err := resetGatingForRefreshed(st, snapsup.InstanceName()); err != nil {
return nil, err
}
}
}
ts := state.NewTaskSet()
targetRevision := snapsup.Revision()
revisionStr := ""
if snapsup.SideInfo != nil {
revisionStr = fmt.Sprintf(" (%s)", targetRevision)
}
// check if we already have the revision locally (alters tasks)
revisionIsLocal := snapst.LastIndex(targetRevision) >= 0
prereq := st.NewTask("prerequisites", fmt.Sprintf(i18n.G("Ensure prerequisites for %q are available"), snapsup.InstanceName()))
prereq.Set("snap-setup", snapsup)
var prepare, prev *state.Task
fromStore := false
// if we have a local revision here we go back to that
if snapsup.SnapPath != "" || revisionIsLocal {
prepare = st.NewTask("prepare-snap", fmt.Sprintf(i18n.G("Prepare snap %q%s"), snapsup.SnapPath, revisionStr))
} else {
fromStore = true
prepare = st.NewTask("download-snap", fmt.Sprintf(i18n.G("Download snap %q%s from channel %q"), snapsup.InstanceName(), revisionStr, snapsup.Channel))
}
prepare.Set("snap-setup", snapsup)
prepare.WaitFor(prereq)
tasks := []*state.Task{prereq, prepare}
addTask := func(t *state.Task) {
t.Set("snap-setup-task", prepare.ID())
t.WaitFor(prev)
tasks = append(tasks, t)
}
prev = prepare
var checkAsserts *state.Task
if fromStore {
// fetch and check assertions
checkAsserts = st.NewTask("validate-snap", fmt.Sprintf(i18n.G("Fetch and check assertions for snap %q%s"), snapsup.InstanceName(), revisionStr))
addTask(checkAsserts)
prev = checkAsserts
}
// mount
if !revisionIsLocal {
mount := st.NewTask("mount-snap", fmt.Sprintf(i18n.G("Mount snap %q%s"), snapsup.InstanceName(), revisionStr))
addTask(mount)
prev = mount
} else {
if snapsup.Flags.RemoveSnapPath {
// If the revision is local, we will not need the
// temporary snap. This can happen when
// e.g. side-loading a local revision again. The
// SnapPath is only needed in the "mount-snap" handler
// and that is skipped for local revisions.
if err := os.Remove(snapsup.SnapPath); err != nil {
return nil, err
}
}
}
// run refresh hooks when updating existing snap, otherwise run install hook further down.
runRefreshHooks := (snapst.IsInstalled() && !snapsup.Flags.Revert)
if runRefreshHooks {
preRefreshHook := SetupPreRefreshHook(st, snapsup.InstanceName())
addTask(preRefreshHook)
prev = preRefreshHook
}
if snapst.IsInstalled() {
// unlink-current-snap (will stop services for copy-data)
stop := st.NewTask("stop-snap-services", fmt.Sprintf(i18n.G("Stop snap %q services"), snapsup.InstanceName()))
stop.Set("stop-reason", snap.StopReasonRefresh)
addTask(stop)
prev = stop
removeAliases := st.NewTask("remove-aliases", fmt.Sprintf(i18n.G("Remove aliases for snap %q"), snapsup.InstanceName()))
addTask(removeAliases)
prev = removeAliases
unlink := st.NewTask("unlink-current-snap", fmt.Sprintf(i18n.G("Make current revision for snap %q unavailable"), snapsup.InstanceName()))
addTask(unlink)
prev = unlink
}
if !release.OnClassic && (snapsup.Type == snap.TypeGadget || (snapsup.Type == snap.TypeKernel && !TestingLeaveOutKernelUpdateGadgetAssets)) {
// XXX: gadget update currently for core systems only
gadgetUpdate := st.NewTask("update-gadget-assets", fmt.Sprintf(i18n.G("Update assets from %s %q%s"), snapsup.Type, snapsup.InstanceName(), revisionStr))
addTask(gadgetUpdate)
prev = gadgetUpdate
}
if !release.OnClassic && snapsup.Type == snap.TypeGadget {
// kernel command line from gadget is for core systems only
gadgetCmdline := st.NewTask("update-gadget-cmdline", fmt.Sprintf(i18n.G("Update kernel command line from gadget %q%s"), snapsup.InstanceName(), revisionStr))
addTask(gadgetCmdline)
prev = gadgetCmdline
}
// copy-data (needs stopped services by unlink)
if !snapsup.Flags.Revert {
copyData := st.NewTask("copy-snap-data", fmt.Sprintf(i18n.G("Copy snap %q data"), snapsup.InstanceName()))
addTask(copyData)
prev = copyData
}
// security
setupSecurity := st.NewTask("setup-profiles", fmt.Sprintf(i18n.G("Setup snap %q%s security profiles"), snapsup.InstanceName(), revisionStr))
addTask(setupSecurity)
prev = setupSecurity
// finalize (wrappers+current symlink)
linkSnap := st.NewTask("link-snap", fmt.Sprintf(i18n.G("Make snap %q%s available to the system"), snapsup.InstanceName(), revisionStr))
addTask(linkSnap)
prev = linkSnap
// auto-connections
autoConnect := st.NewTask("auto-connect", fmt.Sprintf(i18n.G("Automatically connect eligible plugs and slots of snap %q"), snapsup.InstanceName()))
addTask(autoConnect)
prev = autoConnect
// setup aliases
setAutoAliases := st.NewTask("set-auto-aliases", fmt.Sprintf(i18n.G("Set automatic aliases for snap %q"), snapsup.InstanceName()))
addTask(setAutoAliases)
prev = setAutoAliases
setupAliases := st.NewTask("setup-aliases", fmt.Sprintf(i18n.G("Setup snap %q aliases"), snapsup.InstanceName()))
addTask(setupAliases)
prev = setupAliases
if !release.OnClassic && snapsup.Type == snap.TypeSnapd {
// only run for core devices and the snapd snap, run late enough
// so that the task is executed by the new snapd
bootConfigUpdate := st.NewTask("update-managed-boot-config", fmt.Sprintf(i18n.G("Update managed boot config assets from %q%s"), snapsup.InstanceName(), revisionStr))
addTask(bootConfigUpdate)
prev = bootConfigUpdate
}
if runRefreshHooks {
postRefreshHook := SetupPostRefreshHook(st, snapsup.InstanceName())
addTask(postRefreshHook)
prev = postRefreshHook
}
var installHook *state.Task
// only run install hook if installing the snap for the first time
if !snapst.IsInstalled() {
installHook = SetupInstallHook(st, snapsup.InstanceName())
addTask(installHook)
prev = installHook
}
// run new services
startSnapServices := st.NewTask("start-snap-services", fmt.Sprintf(i18n.G("Start snap %q%s services"), snapsup.InstanceName(), revisionStr))
addTask(startSnapServices)
prev = startSnapServices
// Do not do that if we are reverting to a local revision
if snapst.IsInstalled() && !snapsup.Flags.Revert {
var retain int
if err := config.NewTransaction(st).Get("core", "refresh.retain", &retain); err != nil {
// on classic we only keep 2 copies by default
if release.OnClassic {
retain = 2
} else {
retain = 3
}
}
retain-- // we're adding one
seq := snapst.Sequence
currentIndex := snapst.LastIndex(snapst.Current)
// discard everything after "current" (we may have reverted to
// a previous versions earlier)
for i := currentIndex + 1; i < len(seq); i++ {
si := seq[i]
if si.Revision == targetRevision {
// but don't discard this one; its' the thing we're switching to!
continue
}
ts := removeInactiveRevision(st, snapsup.InstanceName(), si.SnapID, si.Revision, snapsup.Type)
ts.WaitFor(prev)
tasks = append(tasks, ts.Tasks()...)
prev = tasks[len(tasks)-1]
}
// make sure we're not scheduling the removal of the target
// revision in the case where the target revision is already in
// the sequence.
for i := 0; i < currentIndex; i++ {
si := seq[i]
if si.Revision == targetRevision {
// we do *not* want to removeInactiveRevision of this one
copy(seq[i:], seq[i+1:])
seq = seq[:len(seq)-1]
currentIndex--
}
}
// normal garbage collect
var inUse boot.InUseFunc
for i := 0; i <= currentIndex-retain; i++ {
if inUse == nil {
var err error
inUse, err = inUseCheck(snapsup.Type)
if err != nil {
return nil, err
}
}
si := seq[i]
if inUse(snapsup.InstanceName(), si.Revision) {
continue
}
ts := removeInactiveRevision(st, snapsup.InstanceName(), si.SnapID, si.Revision, snapsup.Type)
ts.WaitFor(prev)
tasks = append(tasks, ts.Tasks()...)
prev = tasks[len(tasks)-1]
}
addTask(st.NewTask("cleanup", fmt.Sprintf("Clean up %q%s install", snapsup.InstanceName(), revisionStr)))
}
installSet := state.NewTaskSet(tasks...)
installSet.WaitAll(ts)
installSet.MarkEdge(prereq, BeginEdge)
installSet.MarkEdge(setupAliases, BeforeHooksEdge)
if installHook != nil {
installSet.MarkEdge(installHook, HooksEdge)
}
ts.AddAllWithEdges(installSet)
if checkAsserts != nil {
ts.MarkEdge(checkAsserts, DownloadAndChecksDoneEdge)
}
if flags&skipConfigure != 0 {
return installSet, nil
}
// we do not support configuration for bases or the "snapd" snap yet
if snapsup.Type != snap.TypeBase && snapsup.Type != snap.TypeSnapd {
confFlags := 0
notCore := snapsup.InstanceName() != "core"
hasSnapID := snapsup.SideInfo != nil && snapsup.SideInfo.SnapID != ""
if !snapst.IsInstalled() && hasSnapID && notCore {
// installation, run configure using the gadget defaults
// if available, system config defaults (attached to
// "core") are consumed only during seeding, via an
// explicit configure step separate from installing
confFlags |= UseConfigDefaults
}
configSet := ConfigureSnap(st, snapsup.InstanceName(), confFlags)
configSet.WaitAll(ts)
ts.AddAll(configSet)
}
healthCheck := CheckHealthHook(st, snapsup.InstanceName(), snapsup.Revision())
healthCheck.WaitAll(ts)
ts.AddTask(healthCheck)
return ts, nil
}
// ConfigureSnap returns a set of tasks to configure snapName as done during installation/refresh.
func ConfigureSnap(st *state.State, snapName string, confFlags int) *state.TaskSet {
// This is slightly ugly, ideally we would check the type instead
// of hardcoding the name here. Unfortunately we do not have the
// type until we actually run the change.
if snapName == defaultCoreSnapName {
confFlags |= IgnoreHookError
confFlags |= TrackHookError
}
return Configure(st, snapName, nil, confFlags)
}
var Configure = func(st *state.State, snapName string, patch map[string]interface{}, flags int) *state.TaskSet {
panic("internal error: snapstate.Configure is unset")
}
var SetupInstallHook = func(st *state.State, snapName string) *state.Task {
panic("internal error: snapstate.SetupInstallHook is unset")
}
var SetupPreRefreshHook = func(st *state.State, snapName string) *state.Task {
panic("internal error: snapstate.SetupPreRefreshHook is unset")
}
var SetupPostRefreshHook = func(st *state.State, snapName string) *state.Task {
panic("internal error: snapstate.SetupPostRefreshHook is unset")
}
var SetupRemoveHook = func(st *state.State, snapName string) *state.Task {
panic("internal error: snapstate.SetupRemoveHook is unset")
}
var CheckHealthHook = func(st *state.State, snapName string, rev snap.Revision) *state.Task {
panic("internal error: snapstate.CheckHealthHook is unset")
}
var SetupGateAutoRefreshHook = func(st *state.State, snapName string) *state.Task {
panic("internal error: snapstate.SetupAutoRefreshGatingHook is unset")
}
var generateSnapdWrappers = backend.GenerateSnapdWrappers
// FinishRestart will return a Retry error if there is a pending restart
// and a real error if anything went wrong (like a rollback across
// restarts).
// For snapd snap updates this will also rerun wrappers generation to fully
// catch up with any change.
func FinishRestart(task *state.Task, snapsup *SnapSetup) (err error) {
if ok, _ := task.State().Restarting(); ok {
// don't continue until we are in the restarted snapd
task.Logf("Waiting for automatic snapd restart...")
return &state.Retry{}
}
if snapsup.Type == snap.TypeSnapd {
if os.Getenv("SNAPD_REVERT_TO_REV") != "" {
return fmt.Errorf("there was a snapd rollback across the restart")
}
// if we have restarted and snapd was refreshed, then we need to generate
// snapd wrappers again with current snapd, as the logic of generating
// wrappers may have changed between previous and new snapd code.
if !release.OnClassic {
snapdInfo, err := snap.ReadCurrentInfo(snapsup.SnapName())
if err != nil {
return fmt.Errorf("cannot get current snapd snap info: %v", err)
}
// TODO: if future changes to wrappers need one more snapd restart,
// then it should be handled here as well.
if err := generateSnapdWrappers(snapdInfo); err != nil {
return err
}
}
}
// consider kernel and base
deviceCtx, err := DeviceCtx(task.State(), task, nil)
if err != nil {
return err
}
// Check if there was a rollback. A reboot can be triggered by:
// - core (old core16 world, system-reboot)
// - bootable base snap (new core18 world, system-reboot)
// - kernel
//
// On classic and in ephemeral run modes (like install, recover)
// there can never be a rollback so we can skip the check there.
//
// TODO: Detect "snapd" snap daemon-restarts here that
// fallback into the old version (once we have
// better snapd rollback support in core18).
if deviceCtx.RunMode() && !release.OnClassic {
// get the name of the name relevant for booting
// based on the given type
model := deviceCtx.Model()
var bootName string
switch snapsup.Type {
case snap.TypeKernel:
bootName = model.Kernel()
case snap.TypeOS, snap.TypeBase:
bootName = "core"
if model.Base() != "" {
bootName = model.Base()
}
default:
return nil
}
// if it is not a snap related to our booting we are not
// interested
if snapsup.InstanceName() != bootName {
return nil
}
// compare what we think is "current" for snapd with what
// actually booted. The bootloader may revert on a failed
// boot from a bad os/base/kernel to a good one and in this
// case we need to catch this and error accordingly
current, err := boot.GetCurrentBoot(snapsup.Type, deviceCtx)
if err == boot.ErrBootNameAndRevisionNotReady {
return &state.Retry{After: 5 * time.Second}
}
if err != nil {
return err
}
if snapsup.InstanceName() != current.SnapName() || snapsup.SideInfo.Revision != current.SnapRevision() {
// TODO: make sure this revision gets ignored for
// automatic refreshes
return fmt.Errorf("cannot finish %s installation, there was a rollback across reboot", snapsup.InstanceName())
}
}
return nil
}
func contentAttr(attrer interfaces.Attrer) string {
var s string
err := attrer.Attr("content", &s)
if err != nil {
return ""
}
return s
}
func contentIfaceAvailable(st *state.State) map[string]bool {
repo := ifacerepo.Get(st)
contentSlots := repo.AllSlots("content")
avail := make(map[string]bool, len(contentSlots))
for _, slot := range contentSlots {
contentTag := contentAttr(slot)
if contentTag == "" {
continue
}
avail[contentTag] = true
}
return avail
}
// defaultContentPlugProviders takes a snap.Info and returns what
// default providers there are.
func defaultContentPlugProviders(st *state.State, info *snap.Info) []string {
needed := snap.NeededDefaultProviders(info)
if len(needed) == 0 {
return nil
}
avail := contentIfaceAvailable(st)
out := []string{}
for snapInstance, contentTags := range needed {
for _, contentTag := range contentTags {
if !avail[contentTag] {
out = append(out, snapInstance)
break
}
}
}
return out
}
// validateFeatureFlags validates the given snap only uses experimental
// features that are enabled by the user.
func validateFeatureFlags(st *state.State, info *snap.Info) error {
tr := config.NewTransaction(st)
if len(info.Layout) > 0 {
flag, err := features.Flag(tr, features.Layouts)
if err != nil {
return err
}
if !flag {
return fmt.Errorf("experimental feature disabled - test it by setting 'experimental.layouts' to true")
}
}
if info.InstanceKey != "" {
flag, err := features.Flag(tr, features.ParallelInstances)
if err != nil {
return err
}
if !flag {
return fmt.Errorf("experimental feature disabled - test it by setting 'experimental.parallel-instances' to true")
}
}
var hasUserService, usesDbusActivation bool
for _, app := range info.Apps {
if app.IsService() && app.DaemonScope == snap.UserDaemon {
hasUserService = true
}
if len(app.ActivatesOn) != 0 {
usesDbusActivation = true
}
}
if hasUserService {
flag, err := features.Flag(tr, features.UserDaemons)
if err != nil {
return err
}
if !flag {
return fmt.Errorf("experimental feature disabled - test it by setting 'experimental.user-daemons' to true")
}
if !release.SystemctlSupportsUserUnits() {
return fmt.Errorf("user session daemons are not supported on this release")
}
}
if usesDbusActivation {
flag, err := features.Flag(tr, features.DbusActivation)
if err != nil {
return err
}
if !flag {
return fmt.Errorf("experimental feature disabled - test it by setting 'experimental.dbus-activation' to true")
}
}
return nil
}
func ensureInstallPreconditions(st *state.State, info *snap.Info, flags Flags, snapst *SnapState) (Flags, error) {
// if snap is allowed to be devmode via the dangerous model and it's
// confinement is indeed devmode, promote the flags.DevMode to true
if flags.ApplySnapDevMode && info.NeedsDevMode() {
// TODO: what about jail-mode? will we also allow putting devmode
// snaps (i.e. snaps with snap.yaml with confinement: devmode) into
// strict confinement via the model assertion?
flags.DevMode = true
}
if flags.Classic && !info.NeedsClassic() {
// snap does not require classic confinement, silently drop the flag
flags.Classic = false
}
if err := validateInfoAndFlags(info, snapst, flags); err != nil {
return flags, err
}
if err := validateFeatureFlags(st, info); err != nil {
return flags, err
}
if err := checkDBusServiceConflicts(st, info); err != nil {
return flags, err
}
return flags, nil
}
// InstallPath returns a set of tasks for installing a snap from a file path
// and the snap.Info for the given snap.
//
// Note that the state must be locked by the caller.
// The provided SideInfo can contain just a name which results in a
// local revision and sideloading, or full metadata in which case it
// the snap will appear as installed from the store.
func InstallPath(st *state.State, si *snap.SideInfo, path, instanceName, channel string, flags Flags) (*state.TaskSet, *snap.Info, error) {
if si.RealName == "" {
return nil, nil, fmt.Errorf("internal error: snap name to install %q not provided", path)
}
if instanceName == "" {
instanceName = si.RealName
}
deviceCtx, err := DeviceCtxFromState(st, nil)
if err != nil {
return nil, nil, err
}
var snapst SnapState
err = Get(st, instanceName, &snapst)
if err != nil && err != state.ErrNoState {
return nil, nil, err
}
if si.SnapID != "" {
if si.Revision.Unset() {
return nil, nil, fmt.Errorf("internal error: snap id set to install %q but revision is unset", path)
}
}
channel, err = resolveChannel(st, instanceName, snapst.TrackingChannel, channel, deviceCtx)
if err != nil {
return nil, nil, err
}
var instFlags int
if flags.SkipConfigure {
// extract it as a doInstall flag, this is not passed
// into SnapSetup
instFlags |= skipConfigure
}
// It is ok do open the snap file here because we either
// have side info or the user passed --dangerous
info, container, err := backend.OpenSnapFile(path, si)
if err != nil {
return nil, nil, err
}
if err := validateContainer(container, info, logger.Noticef); err != nil {
return nil, nil, err
}
if err := snap.ValidateInstanceName(instanceName); err != nil {
return nil, nil, fmt.Errorf("invalid instance name: %v", err)
}
snapName, instanceKey := snap.SplitInstanceName(instanceName)
if info.SnapName() != snapName {
return nil, nil, fmt.Errorf("cannot install snap %q, the name does not match the metadata %q", instanceName, info.SnapName())
}
info.InstanceKey = instanceKey
flags, err = ensureInstallPreconditions(st, info, flags, &snapst)
if err != nil {
return nil, nil, err
}
// this might be a refresh; check the epoch before proceeding
if err := earlyEpochCheck(info, &snapst); err != nil {
return nil, nil, err
}
snapsup := &SnapSetup{
Base: info.Base,
Prereq: defaultContentPlugProviders(st, info),
SideInfo: si,
SnapPath: path,
Channel: channel,
Flags: flags.ForSnapSetup(),
Type: info.Type(),
PlugsOnly: len(info.Slots) == 0,
InstanceKey: info.InstanceKey,
}
ts, err := doInstall(st, &snapst, snapsup, instFlags, "", inUseFor(deviceCtx))
return ts, info, err
}
// TryPath returns a set of tasks for trying a snap from a file path.
// Note that the state must be locked by the caller.
func TryPath(st *state.State, name, path string, flags Flags) (*state.TaskSet, error) {
flags.TryMode = true
ts, _, err := InstallPath(st, &snap.SideInfo{RealName: name}, path, "", "", flags)
return ts, err
}
// Install returns a set of tasks for installing a snap.
// Note that the state must be locked by the caller.
//
// The returned TaskSet will contain a DownloadAndChecksDoneEdge.
func Install(ctx context.Context, st *state.State, name string, opts *RevisionOptions, userID int, flags Flags) (*state.TaskSet, error) {
return InstallWithDeviceContext(ctx, st, name, opts, userID, flags, nil, "")
}
// InstallWithDeviceContext returns a set of tasks for installing a snap.
// It will query for the snap with the given deviceCtx.
// Note that the state must be locked by the caller.
//
// The returned TaskSet will contain a DownloadAndChecksDoneEdge.
func InstallWithDeviceContext(ctx context.Context, st *state.State, name string, opts *RevisionOptions, userID int, flags Flags, deviceCtx DeviceContext, fromChange string) (*state.TaskSet, error) {
if opts == nil {
opts = &RevisionOptions{}
}
if opts.CohortKey != "" && !opts.Revision.Unset() {
return nil, errors.New("cannot specify revision and cohort")
}
if opts.Channel == "" {
opts.Channel = "stable"
}
var snapst SnapState
err := Get(st, name, &snapst)
if err != nil && err != state.ErrNoState {
return nil, err
}
if snapst.IsInstalled() {
return nil, &snap.AlreadyInstalledError{Snap: name}
}
// need to have a model set before trying to talk the store
deviceCtx, err = DevicePastSeeding(st, deviceCtx)
if err != nil {
return nil, err
}
if err := snap.ValidateInstanceName(name); err != nil {
return nil, fmt.Errorf("invalid instance name: %v", err)
}
sar, err := installInfo(ctx, st, name, opts, userID, flags, deviceCtx)
if err != nil {
return nil, err
}
info := sar.Info
if flags.RequireTypeBase && info.Type() != snap.TypeBase && info.Type() != snap.TypeOS {
return nil, fmt.Errorf("unexpected snap type %q, instead of 'base'", info.Type())
}
flags, err = ensureInstallPreconditions(st, info, flags, &snapst)
if err != nil {
return nil, err
}
tr := config.NewTransaction(st)
checkDiskSpaceInstall, err := features.Flag(tr, features.CheckDiskSpaceInstall)
if err != nil && !config.IsNoOption(err) {
return nil, err
}
if checkDiskSpaceInstall {
// check if there is enough disk space for requested snap and its
// prerequisites.
totalSize, err := installSize(st, []minimalInstallInfo{installSnapInfo{info}}, userID)
if err != nil {
return nil, err
}
requiredSpace := safetyMarginDiskSpace(totalSize)
path := dirs.SnapdStateDir(dirs.GlobalRootDir)
if err := osutilCheckFreeSpace(path, requiredSpace); err != nil {
if _, ok := err.(*osutil.NotEnoughDiskSpaceError); ok {
return nil, &InsufficientSpaceError{
Path: path,
Snaps: []string{info.InstanceName()},
ChangeKind: "install",
}
}
return nil, err
}
}
snapsup := &SnapSetup{
Channel: opts.Channel,
Base: info.Base,
Prereq: defaultContentPlugProviders(st, info),
UserID: userID,