forked from canonical/snapd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers_gadget.go
More file actions
454 lines (401 loc) · 14.1 KB
/
Copy pathhandlers_gadget.go
File metadata and controls
454 lines (401 loc) · 14.1 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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2022 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 devicestate
import (
"errors"
"fmt"
"os"
"path/filepath"
"gopkg.in/tomb.v2"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/boot"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/gadget"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/overlord/configstate/config"
"github.com/snapcore/snapd/overlord/restart"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/snap"
)
func makeRollbackDir(name string) (string, error) {
rollbackDir := filepath.Join(dirs.SnapRollbackDir, name)
if err := os.MkdirAll(rollbackDir, 0750); err != nil {
return "", err
}
return rollbackDir, nil
}
// CurrentGadgetData returns the GadgetData for the currently active gadget.
func CurrentGadgetData(st *state.State, curDeviceCtx snapstate.DeviceContext) (*gadget.GadgetData, error) {
currentInfo, err := snapstate.GadgetInfo(st, curDeviceCtx)
if err != nil && !errors.Is(err, state.ErrNoState) {
return nil, err
}
if currentInfo == nil {
// no current yet
return nil, nil
}
ci, err := gadgetDataFromInfo(currentInfo, curDeviceCtx.Model())
if err != nil {
return nil, fmt.Errorf("cannot read current gadget snap details: %v", err)
}
return ci, nil
}
func pendingGadgetData(snapsup *snapstate.SnapSetup, pendingDeviceCtx snapstate.DeviceContext) (*gadget.GadgetData, error) {
info, err := snap.ReadInfo(snapsup.InstanceName(), snapsup.SideInfo)
if err != nil {
return nil, fmt.Errorf("cannot read candidate gadget snap details: %v", err)
}
gi, err := gadgetDataFromInfo(info, pendingDeviceCtx.Model())
if err != nil {
return nil, fmt.Errorf("cannot read candidate snap gadget metadata: %v", err)
}
return gi, nil
}
var (
gadgetUpdate = gadget.Update
)
func setGadgetRestartRequired(t *state.Task) {
chg := t.Change()
chg.Set("gadget-restart-required", true)
}
func (m *DeviceManager) doUpdateGadgetAssets(t *state.Task, _ *tomb.Tomb) error {
st := t.State()
st.Lock()
defer st.Unlock()
snapsup, err := snapstate.TaskSnapSetup(t)
if err != nil {
return err
}
remodelCtx, err := DeviceCtx(st, t, nil)
if err != nil {
return err
}
if remodelCtx.IsClassicBoot() {
return fmt.Errorf("cannot run update gadget assets task on a classic system")
}
isRemodel := remodelCtx.ForRemodeling()
groundDeviceCtx := remodelCtx.GroundContext()
model := groundDeviceCtx.Model()
if isRemodel {
model = remodelCtx.Model()
}
// be extra paranoid when checking we are installing the right gadget
var updateData *gadget.GadgetData
switch snapsup.Type {
case snap.TypeGadget:
expectedGadgetSnap := model.Gadget()
if snapsup.InstanceName() != expectedGadgetSnap {
return fmt.Errorf("cannot apply gadget assets update from non-model gadget snap %q, expected %q snap",
snapsup.InstanceName(), expectedGadgetSnap)
}
updateData, err = pendingGadgetData(snapsup, remodelCtx)
if err != nil {
return err
}
case snap.TypeKernel:
expectedKernelSnap := model.Kernel()
if snapsup.InstanceName() != expectedKernelSnap {
return fmt.Errorf("cannot apply kernel assets update from non-model kernel snap %q, expected %q snap",
snapsup.InstanceName(), expectedKernelSnap)
}
// now calculate the "update" data, it's the same gadget but
// argumented from a different kernel
updateData, err = CurrentGadgetData(t.State(), groundDeviceCtx)
if err != nil {
return err
}
default:
return fmt.Errorf("internal errror: doUpdateGadgetAssets called with snap type %v", snapsup.Type)
}
currentData, err := CurrentGadgetData(t.State(), groundDeviceCtx)
if err != nil {
return err
}
if currentData == nil {
// no updates during first boot & seeding
return nil
}
// Inject fault during the refresh of the gadget assets
osutil.MaybeInjectFault("refresh-gadget-assets")
// add kernel directories
currentKernelInfo, err := snapstate.CurrentInfo(st, groundDeviceCtx.Model().Kernel())
// XXX: switch to the normal `if err != nil { return err }` pattern
// here once all tests are updated and have a kernel
if err == nil {
currentData.KernelRootDir = currentKernelInfo.MountDir()
updateData.KernelRootDir = currentKernelInfo.MountDir()
}
// if this is a gadget update triggered by an updated kernel we
// need to ensure "updateData.KernelRootDir" points to the new kernel
if snapsup.Type == snap.TypeKernel {
updateKernelInfo, err := snap.ReadInfo(snapsup.InstanceName(), snapsup.SideInfo)
if err != nil {
return fmt.Errorf("cannot read candidate kernel snap details: %v", err)
}
updateData.KernelRootDir = updateKernelInfo.MountDir()
}
snapRollbackDir, err := makeRollbackDir(fmt.Sprintf("%v_%v", snapsup.InstanceName(), snapsup.SideInfo.Revision))
if err != nil {
return fmt.Errorf("cannot prepare update rollback directory: %v", err)
}
var updatePolicy gadget.UpdatePolicyFunc = nil
// Even with a remodel a kernel refresh only updates the kernel assets
if snapsup.Type == snap.TypeKernel {
updatePolicy = gadget.KernelUpdatePolicy
} else if isRemodel {
// use the remodel policy which triggers an update of all
// structures
updatePolicy = gadget.RemodelUpdatePolicy
}
err = func() error {
var updateObserver gadget.ContentUpdateObserver
observeTrustedBootAssets, err := boot.TrustedAssetsUpdateObserverForModel(model, updateData.RootDir)
if err != nil && err != boot.ErrObserverNotApplicable {
return fmt.Errorf("cannot setup asset update observer: %v", err)
}
if err == nil {
updateObserver = observeTrustedBootAssets
defer observeTrustedBootAssets.Done()
}
// do not release the state lock, the update observer may
// attempt to modify modeenv inside, which implicitly is
// guarded by the state lock; on top of that we do not expect
// the update to be moving large amounts of data
if err := gadgetUpdate(model, *currentData, *updateData, snapRollbackDir, updatePolicy, updateObserver); err != nil {
return err
}
// After a gadget update, some recovery bootloaders may need to
// regenerate their config from the persisted boot variables.
if updated, err := boot.ReconfigureRecoveryBootConfig(groundDeviceCtx); err != nil {
return fmt.Errorf("cannot reconfigure recovery boot config: %v", err)
} else if updated {
t.Logf("reconfigured recovery boot config")
}
if updateObserver == nil {
return nil
}
return observeTrustedBootAssets.UpdateBootEntry()
}()
if err != nil {
if err == gadget.ErrNoUpdate {
// no update needed
t.Logf("No gadget assets update needed")
return nil
}
return err
}
if err := os.RemoveAll(snapRollbackDir); err != nil && !os.IsNotExist(err) {
logger.Noticef("failed to remove gadget update rollback directory %q: %v", snapRollbackDir, err)
}
// TODO: consider having the option to do this early via recovery in
// core20, have fallback code as well there
setGadgetRestartRequired(t)
return snapstate.FinishTaskWithRestart(t, state.DoneStatus, restart.RestartSystem, nil)
}
// fromSystemOption tells us if t was created when setting a system
// option for the kernel command line.
func fromSystemOption(t *state.Task) bool {
for _, param := range []string{"cmdline-append", "dangerous-cmdline-append"} {
if t.Has(param) {
return true
}
}
return false
}
func earlyCommitCommandLineAppendTransaction(t *state.Task, st *state.State) error {
tr := config.NewTransaction(st)
for _, param := range []string{"cmdline-append", "dangerous-cmdline-append"} {
if !t.Has(param) {
continue
}
var value string
if err := t.Get(param, &value); err != nil {
return err
}
option := fmt.Sprintf("system.kernel.%s", param)
if err := tr.Set("core", option, value); err != nil {
return err
}
}
tr.Commit()
return nil
}
func (m *DeviceManager) updateGadgetCommandLine(t *state.Task, st *state.State, useCurrentGadget bool) (updated bool, err error) {
logger.Debugf("updating kernel command line")
devCtx, err := DeviceCtx(st, t, nil)
if err != nil {
return false, err
}
if devCtx.Model().Grade() == asserts.ModelGradeUnset {
// pre UC20 system, do nothing
return false, nil
}
var gadgetData *gadget.GadgetData
if !useCurrentGadget {
// command line comes from the new gadget when updating
snapsup, err := snapstate.TaskSnapSetup(t)
if err != nil {
return false, err
}
gadgetData, err = pendingGadgetData(snapsup, devCtx)
if err != nil {
return false, err
}
} else {
// but when undoing or when the change comes from a
// system option (no setup task), we use the current
// gadget (should have been restored in the undo case)
currentGadgetData, err := CurrentGadgetData(st, devCtx)
if err != nil {
return false, err
}
gadgetData = currentGadgetData
}
cmdlineAppend, err := buildAppendedKernelCommandLine(t, gadgetData, devCtx)
if err != nil {
return false, err
}
updated, err = boot.UpdateCommandLineForGadgetComponent(devCtx, gadgetData.RootDir, cmdlineAppend)
if err != nil {
return false, fmt.Errorf("cannot update kernel command line from gadget: %v", err)
}
if updated {
setGadgetRestartRequired(t)
}
return updated, nil
}
func (m *DeviceManager) doUpdateGadgetCommandLine(t *state.Task, _ *tomb.Tomb) (retErr error) {
st := t.State()
st.Lock()
defer st.Unlock()
devCtx, err := DeviceCtx(st, t, nil)
if err != nil {
return err
}
if devCtx.IsClassicBoot() {
return fmt.Errorf("internal error: cannot run update gadget kernel command line task on a classic system")
}
var seeded bool
err = st.Get("seeded", &seeded)
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if !seeded {
// do nothing during first boot & seeding
return nil
}
// Find out if the update has been triggered by setting an extra
// snapd kernel command line fragment.
var fromExtraSnapdFragments bool
err = t.Get("from-extra-snapd-fragments", &fromExtraSnapdFragments)
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
// Find out if the update has been triggered by setting a system
// option that modifies the kernel command line.
fromSysOption := fromSystemOption(t)
defer func() {
if retErr != nil || !fromSysOption {
return
}
// This task is triggered by setting a system option, This is a
// special case where the kernel cmdline configuration is fetched
// from the task state instead of the system configuration options
// because the parent run-hook[configure] task (see configcore/kernel.go)
// does not commit the configuration transaction until after this task
// has finished successfully which leaves a window where other tasks
// might have an inconsistent view of the configuration state and might
// mistakenly overwrite the kernel cmdline with out-of-date values even
// when doing conflict detection or blocking on the task level because it
// will not take into consideration that the parent run-hook[configure]
// task has not committed the configuration transaction yet.
//
// Early committing here on success (given the task is triggered by
// setting a system option) solves this issue and keeps any conflict
// detection or blocking logic working as expected.
//
// TODO: Consider better alternative to double-commit approach below.
if err := earlyCommitCommandLineAppendTransaction(t, st); err != nil {
logger.Debugf("internal error: cannot early commit kernel command line configuration transaction: %v", err)
}
}()
// We use the current gadget kernel command line if the change comes
// from setting a system option.
useCurrentGadget := fromSysOption || fromExtraSnapdFragments
updated, err := m.updateGadgetCommandLine(t, st, useCurrentGadget)
if err != nil {
return err
}
// Any pending extra snapd kernel command line fragments should have
// been applied by now.
//
// Note that the state lock must be held for the duration of the
// task so that we do not accidentally unset the pending state
// that might have been set externally if the state was unlocked.
st.Set(kcmdlinePendingExtraSnapdFragmentsKey, false)
if !updated {
logger.Debugf("no kernel command line update from gadget")
return nil
}
t.Logf("Updated kernel command line")
// TODO: consider optimization to avoid double reboot when the gadget
// snap carries an update to the gadget assets and a change in the
// kernel command line
if fromSysOption || fromExtraSnapdFragments {
logger.Debugf("change did not come from gadget, we do not reboot")
t.SetStatus(state.DoneStatus)
return nil
}
// kernel command line was updated, request a reboot to make it effective
return snapstate.FinishTaskWithRestart(t, state.DoneStatus, restart.RestartSystem, nil)
}
func (m *DeviceManager) undoUpdateGadgetCommandLine(t *state.Task, _ *tomb.Tomb) error {
st := t.State()
st.Lock()
defer st.Unlock()
devCtx, err := DeviceCtx(st, t, nil)
if err != nil {
return err
}
if devCtx.IsClassicBoot() {
return fmt.Errorf("internal error: cannot run undo update gadget kernel command line task on a classic system")
}
var seeded bool
err = st.Get("seeded", &seeded)
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if !seeded {
// do nothing during first boot & seeding
return nil
}
const isUndo = true
updated, err := m.updateGadgetCommandLine(t, st, isUndo)
if err != nil {
return err
}
if !updated {
logger.Debugf("no kernel command line update to undo")
return nil
}
t.Logf("Reverted kernel command line change")
// kernel command line was updated, request a reboot to make it effective
return snapstate.FinishTaskWithRestart(t, state.UndoneStatus, restart.RestartSystem, nil)
}