/
snapstate.go
4438 lines (3859 loc) · 143 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-2023 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"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/asserts/snapasserts"
"github.com/snapcore/snapd/boot"
"github.com/snapcore/snapd/client"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/features"
"github.com/snapcore/snapd/gadget"
"github.com/snapcore/snapd/i18n"
"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/restart"
"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/snapdenv"
"github.com/snapcore/snapd/snapdtool"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/strutil"
)
// control flags for doInstall
const (
skipConfigure = 1 << iota
noRestartBoundaries
)
// control flags for "Configure()"
const (
IgnoreHookError = 1 << iota
UseConfigDefaults
)
const (
BeginEdge = state.TaskSetEdge("begin")
BeforeHooksEdge = state.TaskSetEdge("before-hooks")
HooksEdge = state.TaskSetEdge("hooks")
BeforeMaybeRebootEdge = state.TaskSetEdge("before-maybe-reboot")
MaybeRebootEdge = state.TaskSetEdge("maybe-reboot")
MaybeRebootWaitEdge = state.TaskSetEdge("maybe-reboot-wait")
AfterMaybeRebootWaitEdge = state.TaskSetEdge("after-maybe-reboot-wait")
LastBeforeLocalModificationsEdge = state.TaskSetEdge("last-before-local-modifications")
EndEdge = state.TaskSetEdge("end")
)
const (
firmwareUpdaterSnapID = "EI0D1KHjP8XiwMZKqSjuh6W8zvcowUVP"
snapdDesktopIntegrationSnapID = "IrwRHakqtzhFRHJOOPxKVPU0Kk7Erhcu"
)
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, prqt PrereqTracker) []string
}
type updateParamsFunc func(*snap.Info) (*RevisionOptions, Flags, *SnapState)
type readyUpdateInfo interface {
minimalInstallInfo
SnapSetupForUpdate(st *state.State, params updateParamsFunc, userID int, globalFlags *Flags, prqt PrereqTracker) (*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, prqt PrereqTracker) []string {
return getKeys(defaultProviderContentAttrs(st, ins.Info, prqt))
}
func (ins installSnapInfo) SnapSetupForUpdate(st *state.State, params updateParamsFunc, userID int, globalFlags *Flags, prqt PrereqTracker) (*SnapSetup, *SnapState, error) {
update := ins.Info
revnoOpts, flags, snapst := params(update)
flags.IsAutoRefresh = globalFlags.IsAutoRefresh
flags.IsContinuedAutoRefresh = globalFlags.IsContinuedAutoRefresh
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
}
providerContentAttrs := defaultProviderContentAttrs(st, update, prqt)
snapsup := SnapSetup{
Base: update.Base,
Prereq: getKeys(providerContentAttrs),
PrereqContentAttrs: providerContentAttrs,
Channel: revnoOpts.Channel,
CohortKey: revnoOpts.CohortKey,
UserID: snapUserID,
Flags: flags.ForSnapSetup(),
DownloadInfo: &update.DownloadInfo,
SideInfo: &update.SideInfo,
Type: update.Type(),
Version: update.Version,
PlugsOnly: len(update.Slots) == 0,
InstanceKey: update.InstanceKey,
auxStoreInfo: auxStoreInfo{
Media: update.Media,
// XXX we store this for the benefit of old snapd
Website: update.Website(),
},
ExpectedProvenance: update.SnapProvenance,
}
snapsup.IgnoreRunning = globalFlags.IgnoreRunning
return &snapsup, snapst, nil
}
// pathInfo holds information about a path install
type pathInfo struct {
*snap.Info
path string
sideInfo *snap.SideInfo
}
func (i pathInfo) DownloadSize() int64 {
return i.Size
}
// SnapBase returns the base snap of the snap.
func (i pathInfo) SnapBase() string {
return i.Base
}
func (i pathInfo) Prereq(st *state.State, prqt PrereqTracker) []string {
return getKeys(defaultProviderContentAttrs(st, i.Info, prqt))
}
func (i pathInfo) SnapSetupForUpdate(st *state.State, params updateParamsFunc, _ int, _ *Flags, prqt PrereqTracker) (*SnapSetup, *SnapState, error) {
update := i.Info
_, flags, snapst := params(update)
providerContentAttrs := defaultProviderContentAttrs(st, update, prqt)
snapsup := SnapSetup{
Base: i.Base,
Prereq: getKeys(providerContentAttrs),
PrereqContentAttrs: providerContentAttrs,
SideInfo: i.sideInfo,
SnapPath: i.path,
Flags: flags.ForSnapSetup(),
Type: i.Type(),
Version: i.Version,
PlugsOnly: len(i.Slots) == 0,
InstanceKey: i.InstanceKey,
}
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
}
// refreshRetain returns refresh.retain value if set, or the default value (different for core and classic).
// It deals with potentially wrong type due to lax validation.
func refreshRetain(st *state.State) int {
var val interface{}
// due to lax validation of refresh.retain on set we might end up having a string representing a number here; handle it gracefully
// for backwards compatibility.
err := config.NewTransaction(st).Get("core", "refresh.retain", &val)
var retain int
if err == nil {
switch v := val.(type) {
// this is the expected value; confusingly, since we pass interface{} to Get(), we get json.Number type; if int reference was passed,
// we would get an int instead of json.Number.
case json.Number:
retain, err = strconv.Atoi(string(v))
// not really expected when requesting interface{}.
case int:
retain = v
// we can get string here due to lax validation of refresh.retain on Set in older releases.
case string:
retain, err = strconv.Atoi(v)
default:
logger.Noticef("internal error: refresh.retain system option has unexpected type: %T", v)
}
}
// this covers error from Get() and strconv above.
if err != nil && !config.IsNoOption(err) {
logger.Noticef("internal error: refresh.retain system option is not valid: %v", err)
}
// not set, use default value
if retain == 0 {
// on classic we only keep 2 copies by default
if release.OnClassic {
retain = 2
} else {
retain = 3
}
}
return retain
}
var excludeFromRefreshAppAwareness = func(t snap.Type) bool {
return t == snap.TypeSnapd || t == snap.TypeOS
}
func isDefaultConfigureAllowed(snapsup *SnapSetup) bool {
return isConfigureAllowed(snapsup) && !isCoreSnap(snapsup.InstanceName())
}
func isConfigureAllowed(snapsup *SnapSetup) bool {
// we do not support configuration for bases or the "snapd" snap yet
return snapsup.Type != snap.TypeBase && snapsup.Type != snap.TypeSnapd
}
func configureSnapFlags(snapst *SnapState, snapsup *SnapSetup) int {
confFlags := 0
// config defaults cannot be retrieved without a snap ID
hasSnapID := snapsup.SideInfo != nil && snapsup.SideInfo.SnapID != ""
if !snapst.IsInstalled() && hasSnapID && !isCoreSnap(snapsup.InstanceName()) {
// 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
}
return confFlags
}
func isCoreSnap(snapName string) bool {
return snapName == defaultCoreSnapName
}
func doInstall(st *state.State, snapst *SnapState, snapsup *SnapSetup, flags int, fromChange string, inUseCheck func(snap.Type) (boot.InUseFunc, error)) (*state.TaskSet, error) {
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
}
targetRevision := snapsup.Revision()
revisionStr := fmt.Sprintf(" (%s)", snapsup.Revision())
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)
// When downgrading snapd we want to make sure that it's an exclusive change.
if snapsup.SnapName() == "snapd" {
res, err := strutil.VersionCompare(info.Version, snapsup.Version)
if err != nil {
return nil, fmt.Errorf("cannot compare versions of snapd [cur: %s, new: %s]: %v", info.Version, snapsup.Version, err)
}
// If snapsup.Version was smaller, 1 is returned.
if res == 1 {
if err := checkChangeConflictExclusiveKinds(st, "snapd downgrade", fromChange); err != nil {
return nil, err
}
}
}
if experimentalRefreshAppAwareness && !excludeFromRefreshAppAwareness(snapsup.Type) && !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, snapsup, info); err != nil {
// snap is running; schedule its downloading before notifying to close
var busyErr *timedBusySnapError
if errors.As(err, &busyErr) && snapsup.IsAutoRefresh {
tasks, err := findTasksMatchingKindAndSnap(st, "pre-download-snap", snapsup.InstanceName(), snapsup.Revision())
if err != nil {
return nil, err
}
for _, task := range tasks {
switch task.Status() {
case state.DoStatus, state.DoingStatus:
// there's already a task for this snap/revision combination
return nil, busyErr
}
}
ts := state.NewTaskSet()
preDownTask := st.NewTask("pre-download-snap", fmt.Sprintf(i18n.G("Pre-download snap %q%s from channel %q"), snapsup.InstanceName(), revisionStr, snapsup.Channel))
preDownTask.Set("snap-setup", snapsup)
preDownTask.Set("refresh-info", busyErr.PendingSnapRefreshInfo())
ts.AddTask(preDownTask)
return ts, busyErr
}
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
}
}
}
// 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}
prev = prepare
addTask := func(t *state.Task) {
t.Set("snap-setup-task", prepare.ID())
t.WaitFor(prev)
tasks = append(tasks, t)
}
addTasksFromTaskSet := func(ts *state.TaskSet) {
ts.WaitFor(prev)
tasks = append(tasks, ts.Tasks()...)
prev = tasks[len(tasks)-1]
}
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()))
removeAliases.Set("remove-reason", removeAliasesReasonRefresh)
addTask(removeAliases)
prev = removeAliases
unlink := st.NewTask("unlink-current-snap", fmt.Sprintf(i18n.G("Make current revision for snap %q unavailable"), snapsup.InstanceName()))
unlink.Set("unlink-reason", unlinkReasonRefresh)
addTask(unlink)
prev = unlink
}
// we need to know some of the characteristics of the device - it is
// expected to always have a model/device context at this point.
// TODO in a remodel this would use the old model, we need to fix this
// as needsKernelSetup needs to know the new model for UC2{0,2} -> UC24
// remodel case.
deviceCtx, err := DeviceCtx(st, nil, nil)
if err != nil {
return nil, err
}
// This task is necessary only for UC20+ and hybrid
if snapsup.Type == snap.TypeKernel && needsKernelSetup(deviceCtx) {
setupKernel := st.NewTask("prepare-kernel-snap", fmt.Sprintf(i18n.G("Prepare kernel driver tree for %q%s"), snapsup.InstanceName(), revisionStr))
addTask(setupKernel)
prev = setupKernel
}
if deviceCtx.IsCoreBoot() && (snapsup.Type == snap.TypeGadget || (snapsup.Type == snap.TypeKernel && !TestingLeaveOutKernelUpdateGadgetAssets)) {
// gadget update currently for core boot 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
}
// kernel command line from gadget is for core boot systems only
if deviceCtx.IsCoreBoot() && snapsup.Type == snap.TypeGadget {
// make sure no other active changes are changing the kernel command line
if err := CheckUpdateKernelCommandLineConflict(st, fromChange); err != nil {
return nil, err
}
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)
//
// For essential snaps that require reboots, 'link-snap' is currently
// marked as the edge of that reboot sequence. This means that we currently
// expect 'link-snap' to request the reboot and be the last task to run
// before the reboot takes place (for that lane/change). This task is
// assigned the edge 'MaybeRebootEdge' to indicate this.
//
// 'link-snap' is the last task to run before a reboot for cases like the kernel
// where we would like to try to make sure it boots correctly before we perform
// additional tasks.
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
//
// For essential snaps that require reboots, 'auto-connect' is marked
// as edge 'MaybeRebootWaitEdge' to indicate that this task is expected
// to be the first to run after the reboot (for that lane/change). This
// is noted here to make sure we consider any changes between 'link-snap'
// and 'auto-connect', as that need the edges to be modified as well.
//
// 'auto-connect' is expected to run first after the reboot as it also
// performs some reboot-verification code.
autoConnect := st.NewTask("auto-connect", fmt.Sprintf(i18n.G("Automatically connect eligible plugs and slots of snap %q"), snapsup.InstanceName()))
addTask(autoConnect)
prev = autoConnect
if snapsup.Type == snap.TypeKernel && needsKernelSetup(deviceCtx) {
// This task needs to run after we're back and running the new
// kernel after a reboot was requested in link-snap handler.
setupKernel := st.NewTask("discard-old-kernel-snap-setup", fmt.Sprintf(i18n.G("Discard kernel driver tree for %q%s"), snapsup.InstanceName(), revisionStr))
addTask(setupKernel)
prev = setupKernel
}
// 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 snapsup.Flags.Prefer {
prefer := st.NewTask("prefer-aliases", fmt.Sprintf(i18n.G("Prefer aliases for snap %q"), snapsup.InstanceName()))
addTask(prefer)
prev = prefer
}
if deviceCtx.IsCoreBoot() && snapsup.Type == snap.TypeSnapd {
// make sure no other active changes are changing the kernel command line
if err := CheckUpdateKernelCommandLineConflict(st, fromChange); err != nil {
return nil, err
}
// 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
}
if snapsup.QuotaGroupName != "" {
quotaAddSnapTask, err := AddSnapToQuotaGroup(st, snapsup.InstanceName(), snapsup.QuotaGroupName)
if err != nil {
return nil, err
}
addTask(quotaAddSnapTask)
prev = quotaAddSnapTask
}
// only run default-configure hook if installing the snap for the first time and
// default-configure is allowed
if !snapst.IsInstalled() && isDefaultConfigureAllowed(snapsup) {
defaultConfigureSet := DefaultConfigure(st, snapsup.InstanceName())
addTasksFromTaskSet(defaultConfigureSet)
}
// 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
var cleanupTask *state.Task
if snapst.IsInstalled() && !snapsup.Flags.Revert {
retain := refreshRetain(st)
// if we're not using an already present revision, account for the one being added
if snapst.LastIndex(targetRevision) == -1 {
retain-- // we're adding one
}
seq := snapst.Sequence.Revisions
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.Snap.Revision == targetRevision {
// but don't discard this one; its' the thing we're switching to!
continue
}
ts := removeInactiveRevision(st, snapsup.InstanceName(), si.Snap.SnapID, si.Snap.Revision, snapsup.Type)
addTasksFromTaskSet(ts)
}
// 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.Snap.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.Snap.Revision) {
continue
}
ts := removeInactiveRevision(st, snapsup.InstanceName(), si.Snap.SnapID, si.Snap.Revision, snapsup.Type)
addTasksFromTaskSet(ts)
}
cleanupTask = st.NewTask("cleanup", fmt.Sprintf("Clean up %q%s install", snapsup.InstanceName(), revisionStr))
addTask(cleanupTask)
}
installSet := state.NewTaskSet(tasks...)
installSet.MarkEdge(prereq, BeginEdge)
installSet.MarkEdge(setupAliases, BeforeHooksEdge)
installSet.MarkEdge(setupSecurity, BeforeMaybeRebootEdge)
installSet.MarkEdge(linkSnap, MaybeRebootEdge)
installSet.MarkEdge(autoConnect, MaybeRebootWaitEdge)
installSet.MarkEdge(setAutoAliases, AfterMaybeRebootWaitEdge)
if installHook != nil {
installSet.MarkEdge(installHook, HooksEdge)
}
// if snap is being installed from the store, then the last task before
// any system modifications are done is check validate-snap, otherwise
// it's the prepare-snap
if checkAsserts != nil {
installSet.MarkEdge(checkAsserts, LastBeforeLocalModificationsEdge)
} else {
installSet.MarkEdge(prepare, LastBeforeLocalModificationsEdge)
}
if flags&noRestartBoundaries == 0 {
if err := SetEssentialSnapsRestartBoundaries(st, nil, []*state.TaskSet{installSet}); err != nil {
return nil, err
}
}
if flags&skipConfigure != 0 {
if cleanupTask != nil {
installSet.MarkEdge(cleanupTask, EndEdge)
} else {
installSet.MarkEdge(startSnapServices, EndEdge)
}
return installSet, nil
}
if isConfigureAllowed(snapsup) {
confFlags := configureSnapFlags(snapst, snapsup)
configSet := ConfigureSnap(st, snapsup.InstanceName(), confFlags)
configSet.WaitAll(installSet)
installSet.AddAll(configSet)
}
healthCheck := CheckHealthHook(st, snapsup.InstanceName(), snapsup.Revision())
healthCheck.WaitAll(installSet)
installSet.AddTask(healthCheck)
installSet.MarkEdge(healthCheck, EndEdge)
return installSet, nil
}
func needsKernelSetup(devCtx DeviceContext) bool {
// Must be UC20+ or hybrid
if !devCtx.HasModeenv() {
return false
}
// Check that we have a snapd-generator that will create mount
// units for the drivers tree, for both classic & UC
if devCtx.Classic() {
// We run the generator from the deb package, so check its version
snapdInfoDir := filepath.Join(dirs.GlobalRootDir, dirs.CoreLibExecDir)
debVersion, _, err := snapdtool.SnapdVersionFromInfoFile(snapdInfoDir)
if err != nil {
return false
}
res, err := strutil.VersionCompare(debVersion, "2.62")
if err != nil {
logger.Noticef("cannot compare %q to 2.62: %v", debVersion, err)
return false
}
if res >= 0 {
return true
}
} else {
// We assume core24 onwards has the generator, for older boot bases
// we return false.
// TODO this won't work for a UC2{0,2} -> UC24+ remodel as we
// need the context created from the new model. Get to this
// ASAP after snapd 2.62 release.
baseSn := devCtx.Model().BaseSnap()
if baseSn == nil {
logger.Noticef("internal error: no base in model")
return false
}
// TODO in remodeling we are not getting the right answer,
// how to fix that?
switch baseSn.SnapName() {
case "core20", "core22", "core22-desktop":
return false
default:
return true
}
}
return false
}
func findTasksMatchingKindAndSnap(st *state.State, kind string, snapName string, revision snap.Revision) ([]*state.Task, error) {
var tasks []*state.Task
for _, t := range st.Tasks() {
if t.Kind() != kind {
continue
}
snapsup, _, err := snapSetupAndState(t)
if err != nil {
return nil, err
}
if snapsup.InstanceName() == snapName && snapsup.Revision() == revision {
tasks = append(tasks, t)
}
}
return tasks, 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 isCoreSnap(snapName) {
confFlags |= IgnoreHookError
}
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 DefaultConfigure = func(st *state.State, snapName string) *state.TaskSet {
panic("internal error: snapstate.DefaultConfigure 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 AddSnapToQuotaGroup = func(st *state.State, snapName string, quotaGroup string) (*state.Task, error) {
panic("internal error: snapstate.AddSnapToQuotaGroup is unset")
}
var HasActiveConnection = func(st *state.State, iface string) (bool, error) {
panic("internal error: snapstate.HasActiveConnection 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 snapdenv.Preseeding() {
// nothing to do when preseeding
return nil
}
if ok, _ := restart.Pending(task.State()); 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")
}
snapdInfo, err := snap.ReadCurrentInfo(snapsup.SnapName())
if err != nil {
return fmt.Errorf("cannot get current snapd snap info: %v", err)
}
// Old versions of snapd did not fill in the version field, unintentionally
// triggering snapd downgrade detection logic. Fill in the version from the
// snapd we are currently using.
if snapsup.Version == "" {
snapsup.Version = snapdInfo.Version
if err = SetTaskSnapSetup(task, snapsup); err != nil {
return err
}
}
// 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 {
// TODO: if future changes to wrappers need one more snapd restart,
// then it should be handled here as well.
restart, err := generateSnapdWrappers(snapdInfo, nil)
if err != nil {
return err
}
if restart != nil {
if err := restart.Restart(); 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
//
// If no mode and in ephemeral run modes (like install, recover)
// there can never be a rollback so we can skip the check there.
// For bases we do not reboot in classic.
//
// TODO: Detect "snapd" snap daemon-restarts here that
// fallback into the old version (once we have
// better snapd rollback support in core18).
//
// Applies only to core-like boot, except if classic with modes for
// base/core updates.
if deviceCtx.RunMode() && boot.SnapTypeParticipatesInBoot(snapsup.Type, deviceCtx) {
// 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: