forked from snapcore/snapd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
systems.go
427 lines (390 loc) · 12.7 KB
/
systems.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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2020 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 (
"fmt"
"path/filepath"
"strings"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/boot"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/seed"
"github.com/snapcore/snapd/seed/seedwriter"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/strutil"
)
func checkSystemRequestConflict(st *state.State, systemLabel string) error {
st.Lock()
defer st.Unlock()
var seeded bool
if err := st.Get("seeded", &seeded); err != nil && err != state.ErrNoState {
return err
}
if seeded {
// the system is fully seeded already
return nil
}
// inspect the current system which is stored in modeenv, note we are
// holding the state lock so there is no race against mark-seeded
// clearing recovery system; recovery system is not cleared when seeding
// fails
modeEnv, err := maybeReadModeenv()
if err != nil {
return err
}
if modeEnv == nil {
// non UC20 systems do not support actions, no conflict can
// happen
return nil
}
// not yet fully seeded, hold off requests for the system that is being
// seeded, but allow requests for other systems
if modeEnv.RecoverySystem == systemLabel {
return &snapstate.ChangeConflictError{
ChangeKind: "seed",
Message: "cannot request system action, system is seeding",
}
}
return nil
}
func systemFromSeed(label string, current *currentSystem) (*System, error) {
s, err := seed.Open(dirs.SnapSeedDir, label)
if err != nil {
return nil, fmt.Errorf("cannot open: %v", err)
}
if err := s.LoadAssertions(nil, nil); err != nil {
return nil, fmt.Errorf("cannot load assertions: %v", err)
}
// get the model
model := s.Model()
brand, err := s.Brand()
if err != nil {
return nil, fmt.Errorf("cannot obtain brand: %v", err)
}
system := &System{
Current: false,
Label: label,
Model: model,
Brand: brand,
Actions: defaultSystemActions,
}
if current.sameAs(system) {
system.Current = true
system.Actions = current.actions
}
return system, nil
}
type currentSystem struct {
*seededSystem
actions []SystemAction
}
func (c *currentSystem) sameAs(other *System) bool {
return c != nil &&
c.System == other.Label &&
c.Model == other.Model.Model() &&
c.BrandID == other.Brand.AccountID()
}
func currentSystemForMode(st *state.State, mode string) (*currentSystem, error) {
var system *seededSystem
var actions []SystemAction
var err error
switch mode {
case "run":
actions = currentSystemActions
system, err = currentSeededSystem(st)
case "install":
// there is no current system for install mode
return nil, nil
case "recover":
actions = recoverSystemActions
// recover mode uses modeenv for reference
system, err = seededSystemFromModeenv()
default:
return nil, fmt.Errorf("internal error: cannot identify current system for unsupported mode %q", mode)
}
if err != nil {
return nil, err
}
currentSys := ¤tSystem{
seededSystem: system,
actions: actions,
}
return currentSys, nil
}
func currentSeededSystem(st *state.State) (*seededSystem, error) {
st.Lock()
defer st.Unlock()
var whatseeded []seededSystem
if err := st.Get("seeded-systems", &whatseeded); err != nil {
return nil, err
}
if len(whatseeded) == 0 {
// unexpected
return nil, state.ErrNoState
}
// seeded systems are prepended to the list, so the most recently seeded
// one comes first
return &whatseeded[0], nil
}
func seededSystemFromModeenv() (*seededSystem, error) {
modeEnv, err := maybeReadModeenv()
if err != nil {
return nil, err
}
if modeEnv == nil {
return nil, fmt.Errorf("internal error: modeenv does not exist")
}
if modeEnv.RecoverySystem == "" {
return nil, fmt.Errorf("internal error: recovery system is unset")
}
system, err := systemFromSeed(modeEnv.RecoverySystem, nil)
if err != nil {
return nil, err
}
seededSys := &seededSystem{
System: modeEnv.RecoverySystem,
Model: system.Model.Model(),
BrandID: system.Model.BrandID(),
Revision: system.Model.Revision(),
Timestamp: system.Model.Timestamp(),
// SeedTime is intentionally left unset
}
return seededSys, nil
}
// getInfoFunc is expected to return for a given snap name a snap.Info for that
// snap and whether the snap is present is present. The second bit is relevant
// for non-essential snaps mentioned in the model, which if present and having
// an 'optional' presence in the model, will be added to the recovery system.
type getSnapInfoFunc func(name string) (info *snap.Info, snapIsPresent bool, err error)
// snapWriteObserveFunc is called with the recovery system directory and the
// path to a snap file being written. The snap file may be written to a location
// under the common snaps directory.
type snapWriteObserveFunc func(systemDir, where string) error
// createSystemForModelFromValidatedSnaps creates a new recovery system for the
// specified model with the specified label using the snaps in the database and
// the getInfo function.
//
// The function returns the directory of the new recovery system as well as the
// set of absolute file paths to the new snap files that were written for the
// recovery system - some snaps may be in the recovery system directory while
// others may be in the common snaps directory shared between multiple recovery
// systems on ubuntu-seed.
func createSystemForModelFromValidatedSnaps(model *asserts.Model, label string, db asserts.RODatabase, getInfo getSnapInfoFunc, observeWrite snapWriteObserveFunc) (dir string, err error) {
if model.Grade() == asserts.ModelGradeUnset {
return "", fmt.Errorf("cannot create a system for non UC20 model")
}
logger.Noticef("creating recovery system with label %q for %q", label, model.Model())
// TODO: should that path provided by boot package instead?
recoverySystemDirInRootDir := filepath.Join("/systems", label)
assertedSnapsDir := filepath.Join(boot.InitramfsUbuntuSeedDir, "snaps")
recoverySystemDir := filepath.Join(boot.InitramfsUbuntuSeedDir, recoverySystemDirInRootDir)
wOpts := &seedwriter.Options{
// RW mount of ubuntu-seed
SeedDir: boot.InitramfsUbuntuSeedDir,
Label: label,
}
w, err := seedwriter.New(model, wOpts)
if err != nil {
return "", err
}
optsSnaps := make([]*seedwriter.OptionsSnap, 0, len(model.RequiredWithEssentialSnaps()))
// collect all snaps that are present
modelSnaps := make(map[string]*snap.Info)
getModelSnap := func(name string, essential bool, nonEssentialPresence string) error {
kind := "essential"
if !essential {
kind = "non-essential"
if nonEssentialPresence != "" {
kind = fmt.Sprintf("non-essential but %v", nonEssentialPresence)
}
}
info, present, err := getInfo(name)
if err != nil {
return fmt.Errorf("cannot obtain %v snap information: %v", kind, err)
}
if !essential && !present && nonEssentialPresence == "optional" {
// non-essential snap which is declared as optionally
// present in the model
return nil
}
// grab those
logger.Debugf("%v snap: %v", kind, name)
if !present {
return fmt.Errorf("internal error: %v snap %q not present", kind, name)
}
if _, ok := modelSnaps[info.MountFile()]; ok {
// we've already seen this snap
return nil
}
// present locally
// TODO: for grade dangerous we could have a channel here which is not
// the model channel, handle that here
optsSnaps = append(optsSnaps, &seedwriter.OptionsSnap{
Path: info.MountFile(),
})
modelSnaps[info.MountFile()] = info
return nil
}
for _, sn := range model.EssentialSnaps() {
const essential = true
if err := getModelSnap(sn.SnapName(), essential, ""); err != nil {
return "", err
}
}
// snapd is implicitly needed
const snapdIsEssential = true
if err := getModelSnap("snapd", snapdIsEssential, ""); err != nil {
return "", err
}
for _, sn := range model.SnapsWithoutEssential() {
const essential = false
if err := getModelSnap(sn.SnapName(), essential, sn.Presence); err != nil {
return "", err
}
}
if err := w.SetOptionsSnaps(optsSnaps); err != nil {
return "", err
}
newFetcher := func(save func(asserts.Assertion) error) asserts.Fetcher {
fromDB := func(ref *asserts.Ref) (asserts.Assertion, error) {
return ref.Resolve(db.Find)
}
return asserts.NewFetcher(db, fromDB, save)
}
f, err := w.Start(db, newFetcher)
if err != nil {
return "", err
}
// past this point the system directory is present
localSnaps, err := w.LocalSnaps()
if err != nil {
return recoverySystemDir, err
}
for _, sn := range localSnaps {
info, ok := modelSnaps[sn.Path]
if !ok {
return recoverySystemDir, fmt.Errorf("internal error: no snap info for %q", sn.Path)
}
// TODO: the side info derived here can be different from what
// we have in snap.Info, but getting it this way can be
// expensive as we need to compute the hash, try to find a
// better way
_, aRefs, err := seedwriter.DeriveSideInfo(sn.Path, f, db)
if err != nil {
if !asserts.IsNotFound(err) {
return recoverySystemDir, err
} else if info.SnapID != "" {
// snap info from state must have come
// from the store, so it is unexpected
// if no assertions for it were found
return recoverySystemDir, fmt.Errorf("internal error: no assertions for asserted snap with ID: %v", info.SnapID)
}
}
if err := w.SetInfo(sn, info); err != nil {
return recoverySystemDir, err
}
sn.ARefs = aRefs
}
if err := w.InfoDerived(); err != nil {
return recoverySystemDir, err
}
for {
// get the list of snaps we need in this iteration
toDownload, err := w.SnapsToDownload()
if err != nil {
return recoverySystemDir, err
}
// which should be empty as all snaps should be accounted for
// already
if len(toDownload) > 0 {
which := make([]string, 0, len(toDownload))
for _, sn := range toDownload {
which = append(which, sn.SnapName())
}
return recoverySystemDir, fmt.Errorf("internal error: need to download snaps: %v", strings.Join(which, ", "))
}
complete, err := w.Downloaded()
if err != nil {
return recoverySystemDir, err
}
if complete {
logger.Debugf("snap processing for creating %q complete", label)
break
}
}
for _, warn := range w.Warnings() {
logger.Noticef("WARNING creating system %q: %s", label, warn)
}
unassertedSnaps, err := w.UnassertedSnaps()
if err != nil {
return recoverySystemDir, err
}
if len(unassertedSnaps) > 0 {
locals := make([]string, len(unassertedSnaps))
for i, sn := range unassertedSnaps {
locals[i] = sn.SnapName()
}
logger.Noticef("system %q contains unasserted snaps %s", label, strutil.Quoted(locals))
}
copySnap := func(name, src, dst string) error {
// if the destination snap is in the asserted snaps dir and already
// exists, we don't need to copy it since asserted snaps are shared
if strings.HasPrefix(dst, assertedSnapsDir+"/") && osutil.FileExists(dst) {
return nil
}
// otherwise, unasserted snaps are not shared, so even if the
// destination already exists if it is not in the asserted snaps we
// should copy it
logger.Noticef("copying new seed snap %q from %v to %v", name, src, dst)
if observeWrite != nil {
if err := observeWrite(recoverySystemDir, dst); err != nil {
return err
}
}
return osutil.CopyFile(src, dst, 0)
}
if err := w.SeedSnaps(copySnap); err != nil {
return recoverySystemDir, err
}
if err := w.WriteMeta(); err != nil {
return recoverySystemDir, err
}
bootSnaps, err := w.BootSnaps()
if err != nil {
return recoverySystemDir, err
}
bootWith := &boot.RecoverySystemBootableSet{}
for _, sn := range bootSnaps {
switch sn.Info.Type() {
case snap.TypeKernel:
bootWith.Kernel = sn.Info
bootWith.KernelPath = sn.Path
case snap.TypeGadget:
bootWith.GadgetSnapOrDir = sn.Path
}
}
if err := boot.MakeRecoverySystemBootable(boot.InitramfsUbuntuSeedDir, recoverySystemDirInRootDir, bootWith); err != nil {
return recoverySystemDir, fmt.Errorf("cannot make candidate recovery system %q bootable: %v", label, err)
}
logger.Noticef("created recovery system %q", label)
return recoverySystemDir, nil
}