forked from snapcore/snapd
/
snapstate.go
2467 lines (2147 loc) · 73.4 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-2018 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/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/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")
)
var ErrNothingToDo = errors.New("nothing to do")
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 doInstall(st *state.State, snapst *SnapState, snapsup *SnapSetup, flags int, fromChange string) (*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 := config.GetFeatureFlag(tr, features.RefreshAppAwareness)
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 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 {
// Note that because we are modifying the snap state this block
// must be located after the conflict check done above.
if err := inhibitRefresh(st, snapst, info, SoftNothingRunningRefreshCheck); 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
}
// 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 {
// XXX: gadget update currently for core systems only
gadgetUpdate := st.NewTask("update-gadget-assets", fmt.Sprintf(i18n.G("Update assets from gadget %q%s"), snapsup.InstanceName(), revisionStr))
addTask(gadgetUpdate)
prev = gadgetUpdate
}
// 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 runRefreshHooks {
postRefreshHook := SetupPostRefreshHook(st, snapsup.InstanceName())
addTask(postRefreshHook)
prev = postRefreshHook
}
// 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)
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
for i := 0; i <= currentIndex-retain; i++ {
si := seq[i]
if boot.InUse(snapsup.InstanceName(), si.Revision) {
continue
}
ts := removeInactiveRevision(st, snapsup.InstanceName(), si.SnapID, si.Revision)
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)
ts.AddAll(installSet)
if checkAsserts != nil {
ts.MarkEdge(checkAsserts, DownloadAndChecksDoneEdge)
}
if flags&skipConfigure != 0 {
return installSet, nil
}
var confFlags int
if !snapst.IsInstalled() && snapsup.SideInfo != nil && snapsup.SideInfo.SnapID != "" {
// installation, run configure using the gadget defaults
// if available
confFlags |= UseConfigDefaults
}
// we do not support configuration for bases or the "snapd" snap yet
if snapsup.Type != snap.TypeBase && snapsup.Type != snap.TypeSnapd {
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")
}
// WaitRestart will return a Retry error if there is a pending restart
// and a real error if anything went wrong (like a rollback across
// restarts)
func WaitRestart(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 restart...")
return &state.Retry{}
}
snapInfo, err := snap.ReadInfo(snapsup.InstanceName(), snapsup.SideInfo)
if err != nil {
return err
}
if snapsup.Type == snap.TypeSnapd && os.Getenv("SNAPD_REVERT_TO_REV") != "" {
return fmt.Errorf("there was a snapd rollback across the restart")
}
// If not on classic check there was no rollback. A reboot
// can be triggered by:
// - core (old core16 world, system-reboot)
// - bootable base snap (new core18 world, system-reboot)
//
// TODO: Detect "snapd" snap daemon-restarts here that
// fallback into the old version (once we have
// better snapd rollback support in core18).
if !release.OnClassic {
// TODO: double check that we really rebooted
// otherwise this could be just a spurious restart
// of snapd
model, err := ModelFromTask(task)
if err != nil {
return err
}
bootName := "core"
typ := snap.TypeOS
if model.Base() != "" {
bootName = model.Base()
typ = snap.TypeBase
}
// if it is not a bootable snap we are not interested
if snapsup.InstanceName() != bootName {
return nil
}
current, err := boot.GetCurrentBoot(typ)
if err == boot.ErrBootNameAndRevisionAgain {
return &state.Retry{After: 5 * time.Second}
}
if err != nil {
return err
}
if snapsup.InstanceName() != current.Name || snapInfo.Revision != current.Revision {
// 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, contentTag string) bool {
repo := ifacerepo.Get(st)
for _, slot := range repo.AllSlots("content") {
if contentAttr(slot) == "" {
continue
}
if contentAttr(slot) == contentTag {
return true
}
}
return false
}
// defaultContentPlugProviders takes a snap.Info and returns what
// default providers there are.
func defaultContentPlugProviders(st *state.State, info *snap.Info) []string {
out := []string{}
seen := map[string]bool{}
for _, plug := range info.Plugs {
if plug.Interface == "content" {
if contentAttr(plug) == "" {
continue
}
if !contentIfaceAvailable(st, contentAttr(plug)) {
var dprovider string
err := plug.Attr("default-provider", &dprovider)
if err != nil || dprovider == "" {
continue
}
// The default-provider is a name. However old
// documentation said it is "snapname:ifname",
// we deal with this gracefully by just
// stripping of the part after the ":"
if name := strings.SplitN(dprovider, ":", 2)[0]; !seen[name] {
out = append(out, name)
seen[name] = true
}
}
}
}
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 := config.GetFeatureFlag(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 := config.GetFeatureFlag(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")
}
}
return nil
}
func checkInstallPreconditions(st *state.State, info *snap.Info, flags Flags, snapst *SnapState, deviceCtx DeviceContext) error {
// Check if the snapd can be installed on Ubuntu Core systems, it is
// always ok to install on classic
if info.GetType() == snap.TypeSnapd && !release.OnClassic {
tr := config.NewTransaction(st)
experimentalAllowSnapd, err := config.GetFeatureFlag(tr, features.SnapdSnap)
if err != nil && !config.IsNoOption(err) {
return err
}
if deviceCtx.Model().Base() == "" {
if !experimentalAllowSnapd {
return fmt.Errorf("cannot install snapd snap on a model without a base snap yet")
}
}
}
if err := validateInfoAndFlags(info, snapst, flags); err != nil {
return err
}
if err := validateFeatureFlags(st, info); err != nil {
return err
}
return 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, 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
if flags.Classic && !info.NeedsClassic() {
// snap does not require classic confinement, silently drop the flag
flags.Classic = false
}
// TODO: integrate classic override with the helper
if err := checkInstallPreconditions(st, info, flags, &snapst, deviceCtx); 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.GetType(),
PlugsOnly: len(info.Slots) == 0,
InstanceKey: info.InstanceKey,
}
ts, err := doInstall(st, &snapst, snapsup, instFlags, "")
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)
}
info, err := installInfo(ctx, st, name, opts, userID, deviceCtx)
if err != nil {
return nil, err
}
if flags.RequireTypeBase && info.GetType() != snap.TypeBase && info.GetType() != snap.TypeOS {
return nil, fmt.Errorf("declared snap base %q has unexpected type %q, instead of 'base'", name, info.GetType())
}
if flags.Classic && !info.NeedsClassic() {
// snap does not require classic confinement, silently drop the flag
flags.Classic = false
}
// TODO: integrate classic override with the helper
if err := checkInstallPreconditions(st, info, flags, &snapst, deviceCtx); err != nil {
return nil, err
}
snapsup := &SnapSetup{
Channel: opts.Channel,
Base: info.Base,
Prereq: defaultContentPlugProviders(st, info),
UserID: userID,
Flags: flags.ForSnapSetup(),
DownloadInfo: &info.DownloadInfo,
SideInfo: &info.SideInfo,
Type: info.GetType(),
PlugsOnly: len(info.Slots) == 0,
InstanceKey: info.InstanceKey,
auxStoreInfo: auxStoreInfo{
Media: info.Media,
},
CohortKey: opts.CohortKey,
}
return doInstall(st, &snapst, snapsup, 0, fromChange)
}
// InstallMany installs everything from the given list of names.
// Note that the state must be locked by the caller.
func InstallMany(st *state.State, names []string, userID int) ([]string, []*state.TaskSet, error) {
// need to have a model set before trying to talk the store
deviceCtx, err := DevicePastSeeding(st, nil)
if err != nil {
return nil, nil, err
}
toInstall := make([]string, 0, len(names))
for _, name := range names {
var snapst SnapState
err := Get(st, name, &snapst)
if err != nil && err != state.ErrNoState {
return nil, nil, err
}
if snapst.IsInstalled() {
continue
}
if err := snap.ValidateInstanceName(name); err != nil {
return nil, nil, fmt.Errorf("invalid instance name: %v", err)
}
toInstall = append(toInstall, name)
}
user, err := userFromUserID(st, userID)
if err != nil {
return nil, nil, err
}
installs, err := installCandidates(st, toInstall, "stable", user)
if err != nil {
return nil, nil, err
}
tasksets := make([]*state.TaskSet, 0, len(installs))
for _, info := range installs {
var snapst SnapState
var flags Flags
if err := checkInstallPreconditions(st, info, flags, &snapst, deviceCtx); err != nil {
return nil, nil, err
}
snapsup := &SnapSetup{
Channel: "stable",
Base: info.Base,
Prereq: defaultContentPlugProviders(st, info),
UserID: userID,
Flags: flags.ForSnapSetup(),
DownloadInfo: &info.DownloadInfo,
SideInfo: &info.SideInfo,
Type: info.GetType(),
PlugsOnly: len(info.Slots) == 0,
InstanceKey: info.InstanceKey,
}
ts, err := doInstall(st, &snapst, snapsup, 0, "")
if err != nil {
return nil, nil, err
}
ts.JoinLane(st.NewLane())
tasksets = append(tasksets, ts)
}
return toInstall, tasksets, nil
}
// RefreshCandidates gets a list of candidates for update
// Note that the state must be locked by the caller.
func RefreshCandidates(st *state.State, user *auth.UserState) ([]*snap.Info, error) {
updates, _, _, err := refreshCandidates(context.TODO(), st, nil, user, nil)
return updates, err
}
// ValidateRefreshes allows to hook validation into the handling of refresh candidates.
var ValidateRefreshes func(st *state.State, refreshes []*snap.Info, ignoreValidation map[string]bool, userID int, deviceCtx DeviceContext) (validated []*snap.Info, err error)
// UpdateMany updates everything from the given list of names that the
// store says is updateable. If the list is empty, update everything.
// Note that the state must be locked by the caller.
func UpdateMany(ctx context.Context, st *state.State, names []string, userID int, flags *Flags) ([]string, []*state.TaskSet, error) {
return updateManyFiltered(ctx, st, names, userID, nil, flags, "")
}
// updateFilter is the type of function that can be passed to
// updateManyFromChange so it filters the updates.
//
// If the filter returns true, the update for that snap proceeds. If
// it returns false, the snap is removed from the list of updates to
// consider.
type updateFilter func(*snap.Info, *SnapState) bool
func updateManyFiltered(ctx context.Context, st *state.State, names []string, userID int, filter updateFilter, flags *Flags, fromChange string) ([]string, []*state.TaskSet, error) {
if flags == nil {
flags = &Flags{}
}
user, err := userFromUserID(st, userID)
if err != nil {
return nil, nil, err
}
// need to have a model set before trying to talk the store
deviceCtx, err := DevicePastSeeding(st, nil)
if err != nil {
return nil, nil, err
}
refreshOpts := &store.RefreshOptions{IsAutoRefresh: flags.IsAutoRefresh}
updates, stateByInstanceName, ignoreValidation, err := refreshCandidates(ctx, st, names, user, refreshOpts)
if err != nil {
return nil, nil, err
}
if filter != nil {
actual := updates[:0]
for _, update := range updates {
if filter(update, stateByInstanceName[update.InstanceName()]) {
actual = append(actual, update)
}
}
updates = actual
}
if ValidateRefreshes != nil && len(updates) != 0 {
updates, err = ValidateRefreshes(st, updates, ignoreValidation, userID, deviceCtx)
if err != nil {
// not doing "refresh all" report the error
if len(names) != 0 {
return nil, nil, err
}
// doing "refresh all", log the problems
logger.Noticef("cannot refresh some snaps: %v", err)
}
}
params := func(update *snap.Info) (*RevisionOptions, Flags, *SnapState) {
snapst := stateByInstanceName[update.InstanceName()]
updateFlags := snapst.Flags
if !update.NeedsClassic() && updateFlags.Classic {
// allow updating from classic to strict
updateFlags.Classic = false
}
// setting options to what's in state as multi-refresh doesn't let you change these
opts := &RevisionOptions{
Channel: snapst.Channel,
CohortKey: snapst.CohortKey,
}
return opts, snapst.Flags, snapst
}
return doUpdate(ctx, st, names, updates, params, userID, flags, deviceCtx, fromChange)
}
func doUpdate(ctx context.Context, st *state.State, names []string, updates []*snap.Info, params func(*snap.Info) (*RevisionOptions, Flags, *SnapState), userID int, globalFlags *Flags, deviceCtx DeviceContext, fromChange string) ([]string, []*state.TaskSet, error) {
if globalFlags == nil {
globalFlags = &Flags{}
}
tasksets := make([]*state.TaskSet, 0, len(updates)+2) // 1 for auto-aliases, 1 for re-refresh
refreshAll := len(names) == 0
var nameSet map[string]bool
if len(names) != 0 {
nameSet = make(map[string]bool, len(names))
for _, name := range names {
nameSet[name] = true
}
}
newAutoAliases, mustPruneAutoAliases, transferTargets, err := autoAliasesUpdate(st, names, updates)
if err != nil {
return nil, nil, err
}
reportUpdated := make(map[string]bool, len(updates))
var pruningAutoAliasesTs *state.TaskSet
if len(mustPruneAutoAliases) != 0 {
var err error
pruningAutoAliasesTs, err = applyAutoAliasesDelta(st, mustPruneAutoAliases, "prune", refreshAll, fromChange, func(snapName string, _ *state.TaskSet) {
if nameSet[snapName] {
reportUpdated[snapName] = true
}
})
if err != nil {
return nil, nil, err
}
tasksets = append(tasksets, pruningAutoAliasesTs)
}
// wait for the auto-alias prune tasks as needed
scheduleUpdate := func(snapName string, ts *state.TaskSet) {
if pruningAutoAliasesTs != nil && (mustPruneAutoAliases[snapName] != nil || transferTargets[snapName]) {
ts.WaitAll(pruningAutoAliasesTs)
}
reportUpdated[snapName] = true
}
// first snapd, core, bases, then rest
sort.Stable(snap.ByType(updates))
prereqs := make(map[string]*state.TaskSet)
waitPrereq := func(ts *state.TaskSet, prereqName string) {
preTs := prereqs[prereqName]
if preTs != nil {
ts.WaitAll(preTs)
}
}
// updates is sorted by kind so this will process first core
// and bases and then other snaps
for _, update := range updates {
revnoOpts, flags, snapst := params(update)
flags.IsAutoRefresh = globalFlags.IsAutoRefresh
if err := checkInstallPreconditions(st, update, flags, snapst, deviceCtx); err != nil {
if refreshAll {
logger.Noticef("cannot update %q: %v", update.InstanceName(), err)
continue
}
return nil, nil, err
}
if err := earlyEpochCheck(update, snapst); err != nil {
if refreshAll {
logger.Noticef("cannot update %q: %v", update.InstanceName(), err)
continue
}
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.GetType(),
PlugsOnly: len(update.Slots) == 0,
InstanceKey: update.InstanceKey,
auxStoreInfo: auxStoreInfo{
Media: update.Media,
},