forked from snapcore/snapd
/
handlers.go
3076 lines (2665 loc) · 84 KB
/
handlers.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
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"gopkg.in/tomb.v2"
"github.com/snapcore/snapd/boot"
"github.com/snapcore/snapd/cmd/snaplock/runinhibit"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/features"
"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/configstate/settings"
"github.com/snapcore/snapd/overlord/snapstate/backend"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/progress"
"github.com/snapcore/snapd/release"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/quota"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/strutil"
"github.com/snapcore/snapd/timings"
"github.com/snapcore/snapd/wrappers"
)
// SnapServiceOptions is a hook set by servicestate.
var SnapServiceOptions = func(st *state.State, instanceName string, grps map[string]*quota.Group) (opts *wrappers.SnapServiceOptions, err error) {
panic("internal error: snapstate.SnapServiceOptions is unset")
}
var EnsureSnapAbsentFromQuotaGroup = func(st *state.State, snap string) error {
panic("internal error: snapstate.EnsureSnapAbsentFromQuotaGroup is unset")
}
var SecurityProfilesRemoveLate = func(snapName string, rev snap.Revision, typ snap.Type) error {
panic("internal error: snapstate.SecurityProfilesRemoveLate is unset")
}
// TaskSnapSetup returns the SnapSetup with task params hold by or referred to by the task.
func TaskSnapSetup(t *state.Task) (*SnapSetup, error) {
var snapsup SnapSetup
err := t.Get("snap-setup", &snapsup)
if err != nil && err != state.ErrNoState {
return nil, err
}
if err == nil {
return &snapsup, nil
}
var id string
err = t.Get("snap-setup-task", &id)
if err != nil {
return nil, err
}
ts := t.State().Task(id)
if ts == nil {
return nil, fmt.Errorf("internal error: tasks are being pruned")
}
if err := ts.Get("snap-setup", &snapsup); err != nil {
return nil, err
}
return &snapsup, nil
}
// SetTaskSnapSetup writes the given SnapSetup to the provided task's
// snap-setup-task Task, or to the task itself if the task does not have a
// snap-setup-task (i.e. it _is_ the snap-setup-task)
func SetTaskSnapSetup(t *state.Task, snapsup *SnapSetup) error {
if t.Has("snap-setup") {
// this is the snap-setup-task so just write to the task directly
t.Set("snap-setup", snapsup)
} else {
// this task isn't the snap-setup-task, so go get that and write to that
// one
var id string
err := t.Get("snap-setup-task", &id)
if err != nil {
return err
}
ts := t.State().Task(id)
if ts == nil {
return fmt.Errorf("internal error: tasks are being pruned")
}
ts.Set("snap-setup", snapsup)
}
return nil
}
func snapSetupAndState(t *state.Task) (*SnapSetup, *SnapState, error) {
snapsup, err := TaskSnapSetup(t)
if err != nil {
return nil, nil, err
}
var snapst SnapState
err = Get(t.State(), snapsup.InstanceName(), &snapst)
if err != nil && err != state.ErrNoState {
return nil, nil, err
}
return snapsup, &snapst, nil
}
/* State Locking
do* / undo* handlers should usually lock the state just once with:
st.Lock()
defer st.Unlock()
For tasks doing slow operations (long i/o, networking operations) it's OK
to unlock the state temporarily:
st.Unlock()
err := slowIOOp()
st.Lock()
if err != nil {
...
}
but if a task Get and then Set the SnapState of a snap it must avoid
releasing the state lock in between, other tasks might have
reasons to update the SnapState independently:
// DO NOT DO THIS!:
snapst := ...
snapst.Attr = ...
st.Unlock()
...
st.Lock()
Set(st, snapName, snapst)
if a task really needs to mix mutating a SnapState and releasing the state
lock it should be serialized at the task runner level, see
SnapManger.blockedTask and TaskRunner.SetBlocked
*/
const defaultCoreSnapName = "core"
func defaultBaseSnapsChannel() string {
channel := os.Getenv("SNAPD_BASES_CHANNEL")
if channel == "" {
return "stable"
}
return channel
}
func defaultSnapdSnapsChannel() string {
channel := os.Getenv("SNAPD_SNAPD_CHANNEL")
if channel == "" {
return "stable"
}
return channel
}
func defaultPrereqSnapsChannel() string {
channel := os.Getenv("SNAPD_PREREQS_CHANNEL")
if channel == "" {
return "stable"
}
return channel
}
func linkSnapInFlight(st *state.State, snapName string) (bool, error) {
for _, chg := range st.Changes() {
if chg.Status().Ready() {
continue
}
for _, tc := range chg.Tasks() {
if tc.Status().Ready() {
continue
}
if tc.Kind() == "link-snap" {
snapsup, err := TaskSnapSetup(tc)
if err != nil {
return false, err
}
if snapsup.InstanceName() == snapName {
return true, nil
}
}
}
}
return false, nil
}
func isInstalled(st *state.State, snapName string) (bool, error) {
var snapState SnapState
err := Get(st, snapName, &snapState)
if err != nil && err != state.ErrNoState {
return false, err
}
return snapState.IsInstalled(), nil
}
// timeout for tasks to check if the prerequisites are ready
var prerequisitesRetryTimeout = 30 * time.Second
func (m *SnapManager) doPrerequisites(t *state.Task, _ *tomb.Tomb) error {
st := t.State()
st.Lock()
defer st.Unlock()
perfTimings := state.TimingsForTask(t)
defer perfTimings.Save(st)
// check if we need to inject tasks to install core
snapsup, _, err := snapSetupAndState(t)
if err != nil {
return err
}
// os/base/kernel/gadget cannot have prerequisites other
// than the models default base (or core) which is installed anyway
switch snapsup.Type {
case snap.TypeOS, snap.TypeBase, snap.TypeKernel, snap.TypeGadget:
return nil
}
// snapd is special and has no prereqs
if snapsup.Type == snap.TypeSnapd {
return nil
}
// we need to make sure we install all prereqs together in one
// operation
base := defaultCoreSnapName
if snapsup.Base != "" {
base = snapsup.Base
}
if err := m.installPrereqs(t, base, snapsup.Prereq, snapsup.UserID, perfTimings); err != nil {
return err
}
return nil
}
func (m *SnapManager) installOneBaseOrRequired(st *state.State, snapName string, requireTypeBase bool, channel string, onInFlight error, userID int) (*state.TaskSet, error) {
// The core snap provides everything we need for core16.
coreInstalled, err := isInstalled(st, "core")
if err != nil {
return nil, err
}
if snapName == "core16" && coreInstalled {
return nil, nil
}
// installed already?
isInstalled, err := isInstalled(st, snapName)
if err != nil {
return nil, err
}
if isInstalled {
return nil, nil
}
// in progress?
inFlight, err := linkSnapInFlight(st, snapName)
if err != nil {
return nil, err
}
if inFlight {
return nil, onInFlight
}
// not installed, nor queued for install -> install it
ts, err := Install(context.TODO(), st, snapName, &RevisionOptions{Channel: channel}, userID, Flags{RequireTypeBase: requireTypeBase})
// something might have triggered an explicit install while
// the state was unlocked -> deal with that here by simply
// retrying the operation.
if _, ok := err.(*ChangeConflictError); ok {
return nil, &state.Retry{After: prerequisitesRetryTimeout}
}
return ts, err
}
func (m *SnapManager) installPrereqs(t *state.Task, base string, prereq []string, userID int, tm timings.Measurer) error {
st := t.State()
// We try to install all wanted snaps. If one snap cannot be installed
// because of change conflicts or similar we retry. Only if all snaps
// can be installed together we add the tasks to the change.
var tss []*state.TaskSet
for _, prereqName := range prereq {
var onInFlightErr error = nil
var err error
var ts *state.TaskSet
timings.Run(tm, "install-prereq", fmt.Sprintf("install %q", prereqName), func(timings.Measurer) {
noTypeBaseCheck := false
ts, err = m.installOneBaseOrRequired(st, prereqName, noTypeBaseCheck, defaultPrereqSnapsChannel(), onInFlightErr, userID)
})
if err != nil {
return prereqError("prerequisite", prereqName, err)
}
if ts == nil {
continue
}
tss = append(tss, ts)
}
// for base snaps we need to wait until the change is done
// (either finished or failed)
onInFlightErr := &state.Retry{After: prerequisitesRetryTimeout}
var tsBase *state.TaskSet
var err error
if base != "none" {
timings.Run(tm, "install-prereq", fmt.Sprintf("install base %q", base), func(timings.Measurer) {
requireTypeBase := true
tsBase, err = m.installOneBaseOrRequired(st, base, requireTypeBase, defaultBaseSnapsChannel(), onInFlightErr, userID)
})
if err != nil {
return prereqError("snap base", base, err)
}
}
// on systems without core or snapd need to install snapd to
// make interfaces work - LP: 1819318
var tsSnapd *state.TaskSet
snapdSnapInstalled, err := isInstalled(st, "snapd")
if err != nil {
return err
}
coreSnapInstalled, err := isInstalled(st, "core")
if err != nil {
return err
}
if base != "core" && !snapdSnapInstalled && !coreSnapInstalled {
timings.Run(tm, "install-prereq", "install snapd", func(timings.Measurer) {
noTypeBaseCheck := false
tsSnapd, err = m.installOneBaseOrRequired(st, "snapd", noTypeBaseCheck, defaultSnapdSnapsChannel(), onInFlightErr, userID)
})
if err != nil {
return prereqError("system snap", "snapd", err)
}
}
chg := t.Change()
// add all required snaps, no ordering, this will be done in the
// auto-connect task handler
for _, ts := range tss {
ts.JoinLane(st.NewLane())
chg.AddAll(ts)
}
// add the base if needed, prereqs else must wait on this
if tsBase != nil {
tsBase.JoinLane(st.NewLane())
for _, t := range chg.Tasks() {
t.WaitAll(tsBase)
}
chg.AddAll(tsBase)
}
// add snapd if needed, everything must wait on this
if tsSnapd != nil {
tsSnapd.JoinLane(st.NewLane())
for _, t := range chg.Tasks() {
t.WaitAll(tsSnapd)
}
chg.AddAll(tsSnapd)
}
// make sure that the new change is committed to the state
// together with marking this task done
t.SetStatus(state.DoneStatus)
return nil
}
func prereqError(what, snapName string, err error) error {
if _, ok := err.(*state.Retry); ok {
return err
}
return fmt.Errorf("cannot install %s %q: %v", what, snapName, err)
}
func (m *SnapManager) doPrepareSnap(t *state.Task, _ *tomb.Tomb) error {
st := t.State()
st.Lock()
defer st.Unlock()
snapsup, snapst, err := snapSetupAndState(t)
if err != nil {
return err
}
if snapsup.Revision().Unset() {
// Local revisions start at -1 and go down.
revision := snapst.LocalRevision()
if revision.Unset() || revision.N > 0 {
revision = snap.R(-1)
} else {
revision.N--
}
if !revision.Local() {
panic("internal error: invalid local revision built: " + revision.String())
}
snapsup.SideInfo.Revision = revision
}
t.Set("snap-setup", snapsup)
return nil
}
func (m *SnapManager) undoPrepareSnap(t *state.Task, _ *tomb.Tomb) error {
st := t.State()
st.Lock()
defer st.Unlock()
snapsup, err := TaskSnapSetup(t)
if err != nil {
return err
}
if snapsup.SideInfo == nil || snapsup.SideInfo.RealName == "" {
return nil
}
var logMsg []string
var snapSetup string
dupSig := []string{"snap-install:"}
chg := t.Change()
logMsg = append(logMsg, fmt.Sprintf("change %q: %q", chg.Kind(), chg.Summary()))
for _, t := range chg.Tasks() {
// TODO: report only tasks in intersecting lanes?
tintro := fmt.Sprintf("%s: %s", t.Kind(), t.Status())
logMsg = append(logMsg, tintro)
dupSig = append(dupSig, tintro)
if snapsup, err := TaskSnapSetup(t); err == nil && snapsup.SideInfo != nil {
snapSetup1 := fmt.Sprintf(" snap-setup: %q (%v) %q", snapsup.SideInfo.RealName, snapsup.SideInfo.Revision, snapsup.SideInfo.Channel)
if snapSetup1 != snapSetup {
snapSetup = snapSetup1
logMsg = append(logMsg, snapSetup)
dupSig = append(dupSig, fmt.Sprintf(" snap-setup: %q", snapsup.SideInfo.RealName))
}
}
for _, l := range t.Log() {
// cut of the rfc339 timestamp to ensure duplicate
// detection works in daisy
tStampLen := strings.Index(l, " ")
if tStampLen < 0 {
continue
}
// not tStampLen+1 because the indent is nice
entry := l[tStampLen:]
logMsg = append(logMsg, entry)
dupSig = append(dupSig, entry)
}
}
var ubuntuCoreTransitionCount int
err = st.Get("ubuntu-core-transition-retry", &ubuntuCoreTransitionCount)
if err != nil && err != state.ErrNoState {
return err
}
extra := map[string]string{
"Channel": snapsup.Channel,
"Revision": snapsup.SideInfo.Revision.String(),
}
if ubuntuCoreTransitionCount > 0 {
extra["UbuntuCoreTransitionCount"] = strconv.Itoa(ubuntuCoreTransitionCount)
}
// Only report and error if there is an actual error in the change,
// we could undo things because the user canceled the change.
var isErr bool
for _, tt := range t.Change().Tasks() {
if tt.Status() == state.ErrorStatus {
isErr = true
break
}
}
if isErr && !settings.ProblemReportsDisabled(st) {
st.Unlock()
oopsid, err := errtrackerReport(snapsup.SideInfo.RealName, strings.Join(logMsg, "\n"), strings.Join(dupSig, "\n"), extra)
st.Lock()
if err == nil {
logger.Noticef("Reported install problem for %q as %s", snapsup.SideInfo.RealName, oopsid)
} else {
logger.Debugf("Cannot report problem: %s", err)
}
}
return nil
}
func installInfoUnlocked(st *state.State, snapsup *SnapSetup, deviceCtx DeviceContext) (store.SnapActionResult, error) {
st.Lock()
defer st.Unlock()
opts := &RevisionOptions{Channel: snapsup.Channel, CohortKey: snapsup.CohortKey, Revision: snapsup.Revision()}
return installInfo(context.TODO(), st, snapsup.InstanceName(), opts, snapsup.UserID, Flags{}, deviceCtx)
}
// autoRefreshRateLimited returns the rate limit of auto-refreshes or 0 if
// there is no limit.
func autoRefreshRateLimited(st *state.State) (rate int64) {
tr := config.NewTransaction(st)
var rateLimit string
err := tr.Get("core", "refresh.rate-limit", &rateLimit)
if err != nil {
return 0
}
// NOTE ParseByteSize errors on negative rates
val, err := strutil.ParseByteSize(rateLimit)
if err != nil {
return 0
}
return val
}
func downloadSnapParams(st *state.State, t *state.Task) (*SnapSetup, StoreService, *auth.UserState, error) {
snapsup, err := TaskSnapSetup(t)
if err != nil {
return nil, nil, nil, err
}
deviceCtx, err := DeviceCtx(st, t, nil)
if err != nil {
return nil, nil, nil, err
}
sto := Store(st, deviceCtx)
user, err := userFromUserID(st, snapsup.UserID)
if err != nil {
return nil, nil, nil, err
}
return snapsup, sto, user, nil
}
func (m *SnapManager) doDownloadSnap(t *state.Task, tomb *tomb.Tomb) error {
st := t.State()
var rate int64
st.Lock()
perfTimings := state.TimingsForTask(t)
snapsup, theStore, user, err := downloadSnapParams(st, t)
if snapsup != nil && snapsup.IsAutoRefresh {
// NOTE rate is never negative
rate = autoRefreshRateLimited(st)
}
st.Unlock()
if err != nil {
return err
}
meter := NewTaskProgressAdapterUnlocked(t)
targetFn := snapsup.MountFile()
dlOpts := &store.DownloadOptions{
IsAutoRefresh: snapsup.IsAutoRefresh,
RateLimit: rate,
}
if snapsup.DownloadInfo == nil {
var storeInfo store.SnapActionResult
// COMPATIBILITY - this task was created from an older version
// of snapd that did not store the DownloadInfo in the state
// yet. Therefore do not worry about DeviceContext.
storeInfo, err = installInfoUnlocked(st, snapsup, nil)
if err != nil {
return err
}
timings.Run(perfTimings, "download", fmt.Sprintf("download snap %q", snapsup.SnapName()), func(timings.Measurer) {
err = theStore.Download(tomb.Context(nil), snapsup.SnapName(), targetFn, &storeInfo.DownloadInfo, meter, user, dlOpts)
})
snapsup.SideInfo = &storeInfo.SideInfo
} else {
timings.Run(perfTimings, "download", fmt.Sprintf("download snap %q", snapsup.SnapName()), func(timings.Measurer) {
err = theStore.Download(tomb.Context(nil), snapsup.SnapName(), targetFn, snapsup.DownloadInfo, meter, user, dlOpts)
})
}
if err != nil {
return err
}
snapsup.SnapPath = targetFn
// update the snap setup for the follow up tasks
st.Lock()
t.Set("snap-setup", snapsup)
perfTimings.Save(st)
st.Unlock()
return nil
}
var (
mountPollInterval = 1 * time.Second
)
// hasOtherInstances checks whether there are other instances of the snap, be it
// instance keyed or not
func hasOtherInstances(st *state.State, instanceName string) (bool, error) {
snapName, _ := snap.SplitInstanceName(instanceName)
var all map[string]*json.RawMessage
if err := st.Get("snaps", &all); err != nil && err != state.ErrNoState {
return false, err
}
for otherName := range all {
if otherName == instanceName {
continue
}
if otherSnapName, _ := snap.SplitInstanceName(otherName); otherSnapName == snapName {
return true, nil
}
}
return false, nil
}
func (m *SnapManager) doMountSnap(t *state.Task, _ *tomb.Tomb) error {
st := t.State()
st.Lock()
perfTimings := state.TimingsForTask(t)
snapsup, snapst, err := snapSetupAndState(t)
st.Unlock()
if err != nil {
return err
}
curInfo, err := snapst.CurrentInfo()
if err != nil && err != ErrNoCurrent {
return err
}
m.backend.CurrentInfo(curInfo)
st.Lock()
deviceCtx, err := DeviceCtx(t.State(), t, nil)
st.Unlock()
if err != nil {
return err
}
timings.Run(perfTimings, "check-snap", fmt.Sprintf("check snap %q", snapsup.InstanceName()), func(timings.Measurer) {
err = checkSnap(st, snapsup.SnapPath, snapsup.InstanceName(), snapsup.SideInfo, curInfo, snapsup.Flags, deviceCtx)
})
if err != nil {
return err
}
cleanup := func() {
st.Lock()
defer st.Unlock()
otherInstances, err := hasOtherInstances(st, snapsup.InstanceName())
if err != nil {
t.Errorf("cannot cleanup partial setup snap %q: %v", snapsup.InstanceName(), err)
return
}
// remove snap dir is idempotent so it's ok to always call it in the cleanup path
if err := m.backend.RemoveSnapDir(snapsup.placeInfo(), otherInstances); err != nil {
t.Errorf("cannot cleanup partial setup snap %q: %v", snapsup.InstanceName(), err)
}
}
setupOpts := &backend.SetupSnapOptions{
SkipKernelExtraction: snapsup.SkipKernelExtraction,
}
pb := NewTaskProgressAdapterUnlocked(t)
// TODO Use snapsup.Revision() to obtain the right info to mount
// instead of assuming the candidate is the right one.
var snapType snap.Type
var installRecord *backend.InstallRecord
timings.Run(perfTimings, "setup-snap", fmt.Sprintf("setup snap %q", snapsup.InstanceName()), func(timings.Measurer) {
snapType, installRecord, err = m.backend.SetupSnap(snapsup.SnapPath, snapsup.InstanceName(), snapsup.SideInfo, deviceCtx, setupOpts, pb)
})
if err != nil {
cleanup()
return err
}
// double check that the snap is mounted
var readInfoErr error
for i := 0; i < 10; i++ {
_, readInfoErr = readInfo(snapsup.InstanceName(), snapsup.SideInfo, errorOnBroken)
if readInfoErr == nil {
break
}
if _, ok := readInfoErr.(*snap.NotFoundError); !ok {
break
}
// snap not found, seems is not mounted yet
msg := fmt.Sprintf("expected snap %q revision %v to be mounted but is not", snapsup.InstanceName(), snapsup.Revision())
readInfoErr = fmt.Errorf("cannot proceed, %s", msg)
if i == 0 {
logger.Noticef(msg)
}
time.Sleep(mountPollInterval)
}
if readInfoErr != nil {
timings.Run(perfTimings, "undo-setup-snap", fmt.Sprintf("Undo setup of snap %q", snapsup.InstanceName()), func(timings.Measurer) {
err = m.backend.UndoSetupSnap(snapsup.placeInfo(), snapType, installRecord, deviceCtx, pb)
})
if err != nil {
st.Lock()
t.Errorf("cannot undo partial setup snap %q: %v", snapsup.InstanceName(), err)
st.Unlock()
}
cleanup()
return readInfoErr
}
st.Lock()
// set snapst type for undoMountSnap
t.Set("snap-type", snapType)
if installRecord != nil {
t.Set("install-record", installRecord)
}
st.Unlock()
if snapsup.Flags.RemoveSnapPath {
if err := os.Remove(snapsup.SnapPath); err != nil {
logger.Noticef("Failed to cleanup %s: %s", snapsup.SnapPath, err)
}
}
st.Lock()
perfTimings.Save(st)
st.Unlock()
return nil
}
func (m *SnapManager) undoMountSnap(t *state.Task, _ *tomb.Tomb) error {
st := t.State()
st.Lock()
snapsup, err := TaskSnapSetup(t)
st.Unlock()
if err != nil {
return err
}
st.Lock()
deviceCtx, err := DeviceCtx(t.State(), t, nil)
st.Unlock()
if err != nil {
return err
}
st.Lock()
var typ snap.Type
err = t.Get("snap-type", &typ)
st.Unlock()
// backward compatibility
if err == state.ErrNoState {
typ = "app"
} else if err != nil {
return err
}
var installRecord backend.InstallRecord
st.Lock()
// install-record is optional (e.g. not present in tasks from older snapd)
err = t.Get("install-record", &installRecord)
st.Unlock()
if err != nil && err != state.ErrNoState {
return err
}
pb := NewTaskProgressAdapterUnlocked(t)
if err := m.backend.UndoSetupSnap(snapsup.placeInfo(), typ, &installRecord, deviceCtx, pb); err != nil {
return err
}
st.Lock()
defer st.Unlock()
otherInstances, err := hasOtherInstances(st, snapsup.InstanceName())
if err != nil {
return err
}
return m.backend.RemoveSnapDir(snapsup.placeInfo(), otherInstances)
}
// queryDisabledServices uses wrappers.QueryDisabledServices()
//
// Note this function takes a snap info rather than snapst because there are
// situations where we want to call this on non-current snap infos, i.e. in the
// undo handlers, see undoLinkSnap for an example.
func (m *SnapManager) queryDisabledServices(info *snap.Info, pb progress.Meter) ([]string, error) {
return m.backend.QueryDisabledServices(info, pb)
}
func (m *SnapManager) doUnlinkCurrentSnap(t *state.Task, _ *tomb.Tomb) error {
// called only during refresh when a new revision of a snap is being
// installed
st := t.State()
st.Lock()
defer st.Unlock()
snapsup, snapst, err := snapSetupAndState(t)
if err != nil {
return err
}
oldInfo, err := snapst.CurrentInfo()
if err != nil {
return err
}
tr := config.NewTransaction(st)
experimentalRefreshAppAwareness, err := features.Flag(tr, features.RefreshAppAwareness)
if err != nil && !config.IsNoOption(err) {
return err
}
if experimentalRefreshAppAwareness && !snapsup.Flags.IgnoreRunning {
// Invoke the hard refresh flow. Upon success the returned lock will be
// held to prevent snap-run from advancing until UnlinkSnap, executed
// below, completes.
lock, err := hardEnsureNothingRunningDuringRefresh(m.backend, st, snapst, oldInfo)
if err != nil {
return err
}
defer lock.Close()
}
snapst.Active = false
// snapd current symlink on the refresh path can only replaced by a
// symlink to a new revision of the snapd snap, so only do the actual
// unlink if we're not working on the snapd snap
if oldInfo.Type() != snap.TypeSnapd {
// do the final unlink
linkCtx := backend.LinkContext{
FirstInstall: false,
// This task is only used for unlinking a snap during refreshes so we
// can safely hard-code this condition here.
RunInhibitHint: runinhibit.HintInhibitedForRefresh,
}
err = m.backend.UnlinkSnap(oldInfo, linkCtx, NewTaskProgressAdapterLocked(t))
if err != nil {
return err
}
}
// mark as inactive
Set(st, snapsup.InstanceName(), snapst)
// Notify link snap participants about link changes.
notifyLinkParticipants(t, snapsup.InstanceName())
return nil
}
func (m *SnapManager) undoUnlinkCurrentSnap(t *state.Task, _ *tomb.Tomb) error {
st := t.State()
st.Lock()
defer st.Unlock()
perfTimings := state.TimingsForTask(t)
defer perfTimings.Save(st)
snapsup, snapst, err := snapSetupAndState(t)
if err != nil {
return err
}
oldInfo, err := snapst.CurrentInfo()
if err != nil {
return err
}
deviceCtx, err := DeviceCtx(st, t, nil)
if err != nil {
return err
}
snapst.Active = true
opts, err := SnapServiceOptions(st, snapsup.InstanceName(), nil)
if err != nil {
return err
}
linkCtx := backend.LinkContext{
FirstInstall: false,
ServiceOptions: opts,
}
reboot, err := m.backend.LinkSnap(oldInfo, deviceCtx, linkCtx, perfTimings)
if err != nil {
return err
}
// mark as active again
Set(st, snapsup.InstanceName(), snapst)
// Notify link snap participants about link changes.
notifyLinkParticipants(t, snapsup.InstanceName())
// if we just put back a previous a core snap, request a restart
// so that we switch executing its snapd
m.maybeRestart(t, oldInfo, reboot, deviceCtx)
return nil
}
func (m *SnapManager) doCopySnapData(t *state.Task, _ *tomb.Tomb) error {
st := t.State()
st.Lock()
snapsup, snapst, err := snapSetupAndState(t)
st.Unlock()
if err != nil {
return err
}
newInfo, err := readInfo(snapsup.InstanceName(), snapsup.SideInfo, 0)
if err != nil {
return err
}
oldInfo, err := snapst.CurrentInfo()
if err != nil && err != ErrNoCurrent {
return err
}
pb := NewTaskProgressAdapterUnlocked(t)
if copyDataErr := m.backend.CopySnapData(newInfo, oldInfo, pb); copyDataErr != nil {
if oldInfo != nil {
// there is another revision of the snap, cannot remove
// shared data directory
return copyDataErr
}
// cleanup shared snap data directory
st.Lock()
defer st.Unlock()
otherInstances, err := hasOtherInstances(st, snapsup.InstanceName())
if err != nil {
t.Errorf("cannot undo partial snap %q data copy: %v", snapsup.InstanceName(), err)
return copyDataErr
}
// no other instances of this snap, shared data directory can be
// removed now too
if err := m.backend.RemoveSnapDataDir(newInfo, otherInstances); err != nil {
t.Errorf("cannot undo partial snap %q data copy, failed removing shared directory: %v", snapsup.InstanceName(), err)
}
return copyDataErr
}
return nil
}
func (m *SnapManager) undoCopySnapData(t *state.Task, _ *tomb.Tomb) error {
st := t.State()
st.Lock()
snapsup, snapst, err := snapSetupAndState(t)
st.Unlock()
if err != nil {
return err
}
newInfo, err := readInfo(snapsup.InstanceName(), snapsup.SideInfo, 0)
if err != nil {
return err
}
oldInfo, err := snapst.CurrentInfo()
if err != nil && err != ErrNoCurrent {
return err
}
pb := NewTaskProgressAdapterUnlocked(t)
if err := m.backend.UndoCopySnapData(newInfo, oldInfo, pb); err != nil {
return err