-
Notifications
You must be signed in to change notification settings - Fork 680
Expand file tree
/
Copy pathsnapstate.go
More file actions
4358 lines (3762 loc) · 136 KB
/
Copy pathsnapstate.go
File metadata and controls
4358 lines (3762 loc) · 136 KB
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-2025 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"
"os/exec"
"path/filepath"
"sort"
"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/snap/naming"
"github.com/snapcore/snapd/snapdenv"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/strutil"
)
// control flags for "Configure()"
const (
IgnoreHookError = 1 << iota
UseConfigDefaults
)
const (
BeginEdge = state.TaskSetEdge("begin")
SnapSetupEdge = state.TaskSetEdge("snap-setup")
BeforeHooksEdge = state.TaskSetEdge("before-hooks")
HooksEdge = state.TaskSetEdge("hooks")
MaybeRebootEdge = state.TaskSetEdge("maybe-reboot")
MaybeRebootWaitEdge = state.TaskSetEdge("maybe-reboot-wait")
LastBeforeLocalModificationsEdge = state.TaskSetEdge("last-before-local-modifications")
EndEdge = state.TaskSetEdge("end")
)
// userDaemonsOverrides lists by snap-id a set of well-known snaps for which we
// allow user-daemons directly until we make the feature generally available,
// and not experimental anymore.
//
// TODO: remove this once that is the case
var userDaemonsOverrides = []string{
"EI0D1KHjP8XiwMZKqSjuh6W8zvcowUVP", // firmware-updater snap-id
"IrwRHakqtzhFRHJOOPxKVPU0Kk7Erhcu", // snapd-desktop-integration snap-id
"aoc5lfC8aUd2VL8VpvynUJJhGXp5K6Dj", // prompting-client snap-id
"gjf3IPXoRiipCu9K0kVu52f0H56fIksg", // snap-store snap-id
}
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
var gadgetSetFallbackDefaults = gadget.SetFallbackDefaults
type minimalInstallInfo interface {
InstanceName() string
Type() snap.Type
SnapBase() string
DownloadSize() int64
Prereq(st *state.State, prqt PrereqTracker) []string
}
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 keys(defaultProviderContentAttrs(st, ins.Info, prqt))
}
// 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)
}
// Allows to know if snapd should send desktop notifications to the user.
// If there is a snap connected to the snap-refresh-observe slot, then
// no notification should be sent, delegating all the job to that snap.
func ShouldSendNotificationsToTheUser(st *state.State) (bool, error) {
tr := config.NewTransaction(st)
experimentalRefreshAppAwarenessUX, err := features.Flag(tr, features.RefreshAppAwarenessUX)
if err != nil && !config.IsNoOption(err) {
logger.Noticef("Cannot send notification about pending refresh: %v", err)
return false, err
}
if experimentalRefreshAppAwarenessUX {
// use notices + warnings fallback flow instead
return false, nil
}
markerExists, err := HasActiveConnection(st, "snap-refresh-observe")
if err != nil {
logger.Noticef("Cannot send notification about pending refresh: %v", err)
return false, err
}
if markerExists {
// found snap with marker interface, skip notification
return false, nil
}
return true, nil
}
// safetyMarginDiskSpace returns size plus a safety margin (5Mb)
func safetyMarginDiskSpace(size uint64) uint64 {
return size + 5*1024*1024
}
// 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]any, 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 SetupInstallComponentHook = func(st *state.State, snap, component string) *state.Task {
panic("internal error: snapstate.SetupInstallComponentHook is unset")
}
var SetupPreRefreshComponentHook = func(st *state.State, snap, component string) *state.Task {
panic("internal error: snapstate.SetupPreRefreshComponentHook is unset")
}
var SetupPostRefreshComponentHook = func(st *state.State, snap, component string) *state.Task {
panic("internal error: snapstate.SetupPostRefreshComponentHook is unset")
}
var SetupRemoveComponentHook = func(st *state.State, snap, component string) *state.Task {
panic("internal error: snapstate.SetupRemoveComponentHook 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
// isInvokedWithRevert returns true if the current process was invoked in the
// context of runtime failure handling, most likely by snap-failure.
func isInvokedWithRevert() bool {
return os.Getenv("SNAPD_REVERT_TO_REV") != ""
}
// FinishRestartOptions are options for FinishRestart.
type FinishRestartOptions struct {
// FinishRestartDefault sets the default behavior for FinishRestart in
// case the "finish-restart" task variable is not found, that is, this
// is the behavior for tasks created by older snapd. Tasks that call
// FinishRestart set this value to what would have been the expected
// behavior before the introduction of "finish-restart".
FinishRestartDefault bool
}
// 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, opts FinishRestartOptions) (err error) {
if snapdenv.Preseeding() {
// nothing to do when preseeding
return nil
}
// Check if the task really needs to call this
needsFinishRestart := opts.FinishRestartDefault
if err := task.Get("finish-restart", &needsFinishRestart); err != nil &&
!errors.Is(err, state.ErrNoState) {
return err
}
if !needsFinishRestart {
return nil
}
if restart.Pending(task.State()) != restart.RestartUnset {
// 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 isInvokedWithRevert() {
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 {
err := generateSnapdWrappers(snapdInfo, nil)
if 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:
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
}
// FinishTaskWithRestart will finish a task that needs a restart, by
// setting its status and requesting a restart.
// It should usually be invoked returning its result immediately
// from the caller.
// It delegates the work to restart.FinishTaskWithRestart which decides
// on how the restart will be scheduled.
func FinishTaskWithRestart(task *state.Task, status state.Status, rt restart.RestartType, rebootInfo *boot.RebootInfo) error {
var rebootRequiredSnap string
// If system restart is requested, consider how the change the
// task belongs to is configured (system-restart-immediate) to
// choose whether request an immediate restart or not.
if rt == restart.RestartSystem {
snapsup, err := TaskSnapSetup(task)
if err != nil {
return fmt.Errorf("cannot get snap that triggered a reboot: %v", err)
}
rebootRequiredSnap = snapsup.InstanceName()
chg := task.Change()
var immediate bool
if chg != nil {
// ignore errors intentionally, to follow
// RequestRestart itself which does not
// return errors. If the state is corrupt
// something else will error
chg.Get("system-restart-immediate", &immediate)
}
if immediate {
rt = restart.RestartSystemNow
}
}
return restart.FinishTaskWithRestart(task, status, rt, rebootRequiredSnap, rebootInfo)
}
func isChangeRequestingSnapdRestart(chg *state.Change) bool {
// during refresh of the snapd snap, after the services of new snapd
// have been set up in link-snap, daemon restart is requested, link-snap
// is marked as Done, and the auto-connect task is held off (in Do or
// Doing states) until the restart completes
// TODO: This may need additional handling for snapd restart along the
// Undo path. For instance, 'link-snap' can request a restart in the undo
// direction, making 'setup-profiles' wait for restart.
var haveSnapd, linkDone, autoConnectWaiting bool
for _, tsk := range chg.Tasks() {
kind := tsk.Kind()
switch kind {
case "link-snap", "auto-connect":
// we're only interested in link-snap and auto-connect
default:
continue
}
snapsup, err := TaskSnapSetup(tsk)
if err != nil {
// we're invoked in rollback scenario, things can be
// wrong in a way we cannot anticipate, so let's only
// log the error
logger.Noticef("cannot obtain task snap-setup from %q: %v", tsk.ID(), err)
continue
}
if snapsup.SnapName() != "snapd" {
// not the snap we are looking for
continue
}
haveSnapd = true
status := tsk.Status()
if kind == "link-snap" && status == state.DoneStatus {
linkDone = true
} else if kind == "auto-connect" && (status == state.DoStatus || status == state.DoingStatus) {
autoConnectWaiting = true
}
}
if haveSnapd && linkDone && autoConnectWaiting {
// a snapd snap, for which we have a link-snap task that is
// complete, and an auto-connect task that is waiting to
// execute, this is a scenario which requests a restart of the
// snapd daemon
return true
}
return false
}
var ErrUnexpectedRuntimeRestart = errors.New("unexpected restart at runtime")
// CheckExpectedRestart check whether the current process state indicates that
// it may have been started as a response to an unexpected restart at runtime
// (most likely by snap-failure), and depending on the current changes state
// either returns ErrRecoveryFromUnexpectedRuntimeFailure to indicate that no
// failure handling is needed, or nil indicating that snapd should proceed with
// execution.
func CheckExpectedRestart(st *state.State) error {
if !isInvokedWithRevert() {
return nil
}
// we were invoked by snap-failure, there could be an ongoing refresh of
// the snapd snap which has failed and a revert is pending, but it could
// also be the case that the snapd process just failed at runtime, in
// which case systemd may have triggered an on-failure handling, as such
// proceed with inspecting the state to identify the scenario
for _, chg := range st.Changes() {
if chg.IsReady() {
continue
}
if isChangeRequestingSnapdRestart(chg) {
return nil
}
}
return ErrUnexpectedRuntimeRestart
}
// IsErrAndNotWait returns true if err is not nil and neither state.Wait, it is
// useful for code using FinishTaskWithRestart to not undo work in the presence
// of a state.Wait return.
func IsErrAndNotWait(err error) bool {
if _, ok := err.(*state.Wait); err == nil || ok {
return false
}
return true
}
// defaultProviderContentAttrs takes a snap.Info and returns a map of
// default providers to the value of content attributes they should
// provide. Content attributes already provided by a snap in the system are omitted. What is returned depends on the behavior of the passed PrereqTracker.
func defaultProviderContentAttrs(st *state.State, info *snap.Info, prqt PrereqTracker) map[string][]string {
if prqt == nil {
prqt = snap.SimplePrereqTracker{}
}
repo := ifacerepo.Get(st)
return prqt.MissingProviderContentTags(info, repo)
}
// 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
}
// Some well-known snaps are allowed to use user daemons,
// irrespective of the feature flag state.
//
// TODO: remove the special case once
// experimental.user-daemons is the default
if !flag && !strutil.ListContains(userDaemonsOverrides, info.SnapID) {
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
}
// maintain the classic flag for already classic-confined snaps, assuming
// we're not switching to jail-mode or devmode
if !flags.JailMode && !flags.DevMode {
flags.Classic = flags.Classic || snapst.Classic
}
if flags.Classic && !info.NeedsClassic() {
// snap does not require classic confinement, silently drop the flag
flags.Classic = false
}
// Implicitly set --unaliased flag for parallel installs to avoid
// alias conflicts with the main snap
if !snapst.IsInstalled() && !flags.Prefer && info.InstanceKey != "" {
flags.Unaliased = true
}
if err := validateInfoAndFlags(info, snapst, flags); err != nil {
return flags, err
}
if err := validateFeatureFlags(st, info); err != nil {
return flags, fmt.Errorf("feature flag validation failed for snap %q: %w", info.InstanceName(), err)
}
// TODO: if we implement a --disabled flag for install we should skip the
// dbus and desktop-file-ids checks below.
if err := checkDBusServiceConflicts(st, info); err != nil {
return flags, err
}
if err := checkDesktopFileIDsConflicts(st, info); err != nil {
return flags, err
}
return flags, nil
}
// A PrereqTracker helps tracking snap prerequisites for one or across
// multiple snap operations. Depending of usage context implementations
// can be stateful or stateless.
// Functions taking a PrereqTracker accept nil and promise to call
// Add once for any target snap.
type PrereqTracker interface {
// Add adds a snap for tracking.
Add(*snap.Info)
// MissingProviderContentTags returns a map keyed by the names of all
// missing default-providers for the content plugs that the given
// snap.Info needs. The map values are the corresponding content tags.
// Different prerequisites trackers might decide in different
// ways which providers are missing. Either making assumptions about
// the snap operations that are being set up or considering
// just the snap info and repo.
// In the latter case if repo is not nil, any content tag provided by
// an existing slot in it should be considered already available and
// filtered out from the result. info might or might have not been
// passed already to Add. snapstate uses the result to decide to
// install providers automatically.
MissingProviderContentTags(info *snap.Info, repo snap.InterfaceRepo) map[string][]string
}
// 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, prqt PrereqTracker) (*state.TaskSet, *snap.Info, error) {
target := PathInstallGoal(PathSnap{
InstanceName: instanceName,
Path: path,
SideInfo: si,
RevOpts: RevisionOptions{Channel: channel},
})
// TODO have caller pass a context
info, ts, err := InstallOne(context.Background(), st, target, Options{
Flags: flags,
PrereqTracker: prqt,
})
if err != nil {
return nil, nil, err
}
return ts, info, nil
}
// 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, nil)
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 LastBeforeLocalModificationsEdge
// identifying the last task before the first task that introduces system
// modifications.
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, nil, "")
}
// InstallWithDeviceContext returns a set of tasks for installing a snap.
// It will query the store for the snap with the given deviceCtx.
// Note that the state must be locked by the caller.
//
// The returned TaskSet will contain a LastBeforeLocalModificationsEdge
// identifying the last task before the first task that introduces system
// modifications.
func InstallWithDeviceContext(ctx context.Context, st *state.State, name string, opts *RevisionOptions, userID int, flags Flags, prqt PrereqTracker, deviceCtx DeviceContext, fromChange string) (*state.TaskSet, error) {
logger.Debugf("installing with device context %s", name)
if opts == nil {
opts = &RevisionOptions{}
}
target := StoreInstallGoal(StoreSnap{
InstanceName: name,
RevOpts: *opts,
})
_, ts, err := InstallOne(ctx, st, target, Options{
Flags: flags,
UserID: userID,
ConflictOptions: ConflictOptions{FromChange: fromChange},
PrereqTracker: prqt,
DeviceCtx: deviceCtx,
})
if err != nil {
return nil, err
}
return ts, nil
}
// InstallPathWithDeviceContext returns a set of tasks for installing a local snap.
// Note that the state must be locked by the caller.
//
// The returned TaskSet will contain a LastBeforeLocalModificationsEdge
// identifying the last task before the first task that introduces system
// modifications.
func InstallPathWithDeviceContext(st *state.State, si *snap.SideInfo, path, name string,
opts *RevisionOptions, userID int, flags Flags, prqt PrereqTracker,
deviceCtx DeviceContext, fromChange string) (*state.TaskSet, error) {
logger.Debugf("installing from local file with device context %s", name)
if opts == nil {
opts = &RevisionOptions{}
}
target := PathInstallGoal(PathSnap{
InstanceName: name,
Path: path,
SideInfo: si,
RevOpts: *opts,
})
_, ts, err := InstallOne(context.Background(), st, target, Options{
Flags: flags,
UserID: userID,
ConflictOptions: ConflictOptions{FromChange: fromChange},
PrereqTracker: prqt,
DeviceCtx: deviceCtx,
})
if err != nil {
return nil, err
}
return ts, nil
}
// Download returns a set of tasks for downloading a snap and components into
// the given directory. The snap.Info for the snap that is downloaded is also
// returned. The tasks that are returned also download and validate the snap's
// and components' assertions. Prerequisites for the snap are not downloaded.
//
// TODO: this function will soon return an error if downloadDir ==
// dirs.SnapBlobDir.
func Download(
ctx context.Context,
st *state.State,
name string,
components []string,
downloadDir string,
revOpts RevisionOptions,
opts Options,
) (*state.TaskSet, *snap.Info, error) {
const skipSnapDownload = false
return downloadTasks(ctx, st, name, components, downloadDir, skipSnapDownload, revOpts, opts)
}
// DownloadComponents returns a set of tasks for downloading the given snap
// components into the given directory. The tasks that are returned will also
// download and validate the components' assertions.
//
// TODO: this function will soon return an error if downloadDir ==
// dirs.SnapBlobDir.
func DownloadComponents(
ctx context.Context,
st *state.State,
name string,
components []string,
downloadDir string,
revOpts RevisionOptions,
opts Options,
) (*state.TaskSet, error) {
const skipSnapDownload = true
ts, _, err := downloadTasks(ctx, st, name, components, downloadDir, skipSnapDownload, revOpts, opts)
if err != nil {
return nil, err
}
return ts, nil
}
func downloadTasks(
ctx context.Context,
st *state.State,
name string,
components []string,
downloadDir string,
skipSnapDownload bool,
revOpts RevisionOptions,
opts Options,
) (*state.TaskSet, *snap.Info, error) {
if downloadDir == "" {
return nil, nil, errors.New("internal error: must specify directory to download to")
}
if revOpts.CohortKey != "" && !revOpts.Revision.Unset() {
return nil, nil, errors.New("internal error: cannot specify revision and cohort")
}
if revOpts.Channel == "" {
revOpts.Channel = "stable"
}
if revOpts.ValidationSets == nil {
revOpts.ValidationSets = snapasserts.NewValidationSets()
}
if err := snap.ValidateInstanceName(name); err != nil {
return nil, nil, fmt.Errorf("invalid instance name: %v", err)
}
sar, err := sendOneDownloadAction(ctx, st, StoreSnap{
InstanceName: name,
Components: components,
RevOpts: revOpts,
}, opts)
if err != nil {
return nil, nil, err
}
info := sar.Info
if opts.PrereqTracker != nil {
opts.PrereqTracker.Add(info)
}
if opts.Flags.RequireTypeBase && info.Type() != snap.TypeBase && info.Type() != snap.TypeOS {
return nil, nil, fmt.Errorf("unexpected snap type %q, instead of 'base'", info.Type())
}
snapsup := &SnapSetup{
Channel: revOpts.Channel,
Base: info.Base,
UserID: opts.UserID,
Flags: opts.Flags.ForSnapSetup(),
DownloadInfo: &info.DownloadInfo,
SideInfo: &info.SideInfo,
Type: info.Type(),
Version: info.Version,
InstanceKey: info.InstanceKey,
CohortKey: revOpts.CohortKey,
ExpectedProvenance: info.SnapProvenance,
DownloadBlobDir: downloadDir,
ComponentExclusiveOperation: skipSnapDownload,
}
if sar.RedirectChannel != "" {
snapsup.Channel = sar.RedirectChannel
}
compsups, err := componentTargetsFromActionResult("download", sar, components)
if err != nil {
return nil, nil, fmt.Errorf("cannot extract components from snap resources: %w", err)
}
for i := range compsups {
compsups[i].DownloadBlobDir = downloadDir
}
if err := checkSnapAgainstValidationSets(sar.Info, compsups, "download", revOpts.ValidationSets); err != nil {
return nil, nil, err
}
ts := state.NewTaskSet()
var snapsupTask, prev *state.Task
addTask := func(t *state.Task) {
ts.AddTask(t)
if prev == nil {
t.Set("snap-setup", snapsup)
snapsupTask = t
ts.MarkEdge(t, BeginEdge)
ts.MarkEdge(t, SnapSetupEdge)
} else {
t.WaitFor(prev)
t.Set("snap-setup-task", snapsupTask.ID())
}
prev = t
}
if !skipSnapDownload {
// TODO:COMPS: support checking for available space for components
toDownloadTo := filepath.Dir(snapsup.BlobPath())
if err := checkDiskSpaceDownload([]minimalInstallInfo{installSnapInfo{info}}, toDownloadTo); err != nil {
return nil, nil, err
}
revisionStr := fmt.Sprintf(" (%s)", snapsup.Revision())
download := st.NewTask("download-snap", fmt.Sprintf(i18n.G("Download snap %q%s from channel %q"), snapsup.InstanceName(), revisionStr, snapsup.Channel))
addTask(download)
validate := st.NewTask("validate-snap", fmt.Sprintf(i18n.G("Fetch and check assertions for snap %q%s"), snapsup.InstanceName(), revisionStr))
addTask(validate)
}
compsupIDs := make([]string, 0, len(compsups))
for _, c := range compsups {
rev := fmt.Sprintf(" (%s)", c.CompSideInfo.Revision)
download := st.NewTask("download-component", fmt.Sprintf(i18n.G("Download component %q%s"), c.ComponentName(), rev))
download.Set("component-setup", c)
addTask(download)
compsupTaskID := download.ID()
// even if the component itself is already installed, it might not have
// been installed with the same snap revision. in that case,
// validate-component will fetch new assertions from the store.
validate := st.NewTask("validate-component", fmt.Sprintf(
i18n.G("Fetch and check assertions for component %q%s"), c.ComponentName(), rev),
)
validate.Set("component-setup-task", compsupTaskID)
addTask(validate)
compsupIDs = append(compsupIDs, compsupTaskID)
}
snapsupTask.Set("component-setup-tasks", compsupIDs)
// since nothing in this function does any "local" modifications, we just
// set this edge on the last task in the chain
ts.MarkEdge(prev, LastBeforeLocalModificationsEdge)
return ts, info, nil
}
func validatedInfoFromPathAndSideInfo(instanceName string, path string, si *snap.SideInfo) (*snap.Info, error) {
var info *snap.Info
info, cont, err := backend.OpenSnapFile(path, si)
if err != nil {
return nil, fmt.Errorf("cannot open snap file: %v", err)
}
if err := validateContainer(cont, info, logger.Noticef); err != nil {
return nil, err
}
snapName, instanceKey := snap.SplitInstanceName(instanceName)
if info.SnapName() != snapName {
return nil, fmt.Errorf("cannot install snap %q: instance name prefix does not match snap name: %s != %s", instanceName, snapName, info.SnapName())
}
info.InstanceKey = instanceKey
return info, nil
}
// InstallPathMany returns a set of tasks for installing snaps from a file paths
// and snap.Infos.
//
// The state must be locked by the caller.
// The provided SideInfos can contain just a name which results in a
// local revision and sideloading, or full metadata in which case
// the snaps will appear as installed from the store.
func InstallPathMany(ctx context.Context, st *state.State, sideInfos []*snap.SideInfo, paths []string, userID int, flags *Flags) ([]*state.TaskSet, error) {
if len(paths) != len(sideInfos) {
return nil, fmt.Errorf("internal error: number of paths and side infos must match: %d != %d", len(paths), len(sideInfos))
}
if flags == nil {
flags = &Flags{}
}
// this is to maintain backwards compatibility with the old behavior of
// InstallPathMany
if flags.Transaction == "" {