forked from canonical/snapd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevicemgr.go
More file actions
3513 lines (3037 loc) · 107 KB
/
Copy pathdevicemgr.go
File metadata and controls
3513 lines (3037 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2024 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 (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/asserts/sysdb"
"github.com/snapcore/snapd/boot"
"github.com/snapcore/snapd/client"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/gadget"
"github.com/snapcore/snapd/gadget/device"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/kernel/fde"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/osutil/keyboard"
"github.com/snapcore/snapd/overlord/assertstate"
"github.com/snapcore/snapd/overlord/auth"
"github.com/snapcore/snapd/overlord/configstate/config"
"github.com/snapcore/snapd/overlord/devicestate/internal"
"github.com/snapcore/snapd/overlord/fdestate"
"github.com/snapcore/snapd/overlord/hookstate"
"github.com/snapcore/snapd/overlord/install"
"github.com/snapcore/snapd/overlord/restart"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/overlord/storecontext"
"github.com/snapcore/snapd/overlord/swfeats"
"github.com/snapcore/snapd/progress"
"github.com/snapcore/snapd/release"
"github.com/snapcore/snapd/secboot"
"github.com/snapcore/snapd/secboot/keys"
"github.com/snapcore/snapd/seed"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/snapfile"
"github.com/snapcore/snapd/snapdenv"
"github.com/snapcore/snapd/strutil"
"github.com/snapcore/snapd/sysconfig"
"github.com/snapcore/snapd/systemd"
"github.com/snapcore/snapd/timeutil"
"github.com/snapcore/snapd/timings"
)
var (
cloudInitStatus = sysconfig.CloudInitStatus
restrictCloudInit = sysconfig.RestrictCloudInit
secbootMarkSuccessful = secboot.MarkSuccessful
osutilBootID = osutil.BootID
fdestateAttemptAutoRepairIfNeeded = fdestate.AttemptAutoRepairIfNeeded
)
var (
becomeOperationalChangeKind = swfeats.RegisterChangeKind("become-operational")
seedChangeKind = swfeats.RegisterChangeKind("seed")
installSystemChangeKind = swfeats.RegisterChangeKind("install-system")
factoryResetChangeKind = swfeats.RegisterChangeKind("factory-reset")
)
func init() {
swfeats.RegisterEnsure("DeviceManager", "ensureOperational")
swfeats.RegisterEnsure("DeviceManager", "ensureSeeded")
swfeats.RegisterEnsure("DeviceManager", "ensureAutoImportAssertions")
swfeats.RegisterEnsure("DeviceManager", "ensureSerialBoundSystemUserAssertionsProcessed")
swfeats.RegisterEnsure("DeviceManager", "ensureFDE")
swfeats.RegisterEnsure("DeviceManager", "ensureBootOk")
swfeats.RegisterEnsure("DeviceManager", "ensureCloudInitRestricted")
swfeats.RegisterEnsure("DeviceManager", "ensureInstalled")
swfeats.RegisterEnsure("DeviceManager", "ensureFactoryReset")
swfeats.RegisterEnsure("DeviceManager", "ensureSeedInConfig")
swfeats.RegisterEnsure("DeviceManager", "ensureSeedInConfig")
swfeats.RegisterEnsure("DeviceManager", "ensureTriedRecoverySystem")
swfeats.RegisterEnsure("DeviceManager", "ensurePostFactoryReset")
swfeats.RegisterEnsure("DeviceManager", "ensureExpiredUsersRemoved")
swfeats.RegisterEnsure("DeviceManager", "ensureEarlyBootXKBConfigUpdated")
swfeats.RegisterEnsure("DeviceManager", "ensureExtraSnapdKernelCommandLineFragmentsApplied")
snapstate.RegisterResealingTaskKind("set-model")
snapstate.RegisterResealingTaskKind("create-recovery-system")
snapstate.RegisterResealingTaskKind("remove-recovery-system")
snapstate.RegisterResealingTaskKind("finalize-recovery-system")
snapstate.RegisterResealingTaskKind("update-managed-boot-config")
snapstate.RegisterResealingTaskKind("update-gadget-cmdline")
snapstate.RegisterResealingTaskKind("update-gadget-assets")
}
// EarlyConfig is a hook set by configstate that can process early configuration
// during managers' startup.
var EarlyConfig func(st *state.State, preloadGadget func() (sysconfig.Device, *gadget.Info, error)) error
// ErrNoDeviceIdentityYet is returned when the device doesn't have a serial assertion.
// It's a special case of ErrNoState.
var ErrNoDeviceIdentityYet = &noDeviceIdentityYetError{}
// noDeviceIdentityYetError is returned when the device doesn't have a serial assertion.
type noDeviceIdentityYetError struct{}
func (e *noDeviceIdentityYetError) Error() string {
return "device has no identity yet"
}
func (e *noDeviceIdentityYetError) Is(err error) bool {
_, ok := err.(*noDeviceIdentityYetError)
return ok || errors.Is(err, state.ErrNoState)
}
// StateDeviceInitialized represents another manager that can be
// notified when the device manager has been started.
type StateDeviceInitialized interface {
// DeviceInitialized is called when StartUp has finished on
// DeviceManager. There are no use case for returning an error
// so far.
DeviceInitialized()
}
// DeviceManager is responsible for managing the device identity and device
// policies.
type DeviceManager struct {
// sysMode is the system mode from modeenv or "" on pre-UC20,
// use SystemMode instead
sysMode string
// saveAvailable keeps track whether /var/lib/snapd/save
// is available, i.e. exists and is mounted from ubuntu-save
// if the latter exists.
saveAvailable bool
state *state.State
hookMgr *hookstate.HookManager
cachedKeypairMgr asserts.KeypairManager
// newStore can make new stores for remodeling
newStore func(storecontext.DeviceBackend) snapstate.StoreService
bootRevisionsUpdated bool
fdeRan bool
seedTimings *timings.Timings
// this is used during early phases until seeding is under way
earlyDeviceSeed seed.Seed
// these are details about the chosen seed we will be seeding from,
// set and valid only before seeding has happened. Should not be
// used by tasks that are not explicitly happening prior to system being marked seeded.
seedLabel, seedMode string
seedChosen bool
populateStateFromSeed func(timings.Measurer) ([]*state.TaskSet, error)
ensureSeedInConfigRan bool
ensureBootOkRan bool
ensureInstalledRan bool
ensureFactoryResetRan bool
ensurePostFactoryResetRan bool
ensureTriedRecoverySystemRan bool
ensureEarlyBootLocaleConfigUpdatedRan bool
cloudInitAlreadyRestricted bool
cloudInitErrorAttemptStart *time.Time
cloudInitEnabledInactiveAttemptStart *time.Time
lastBecomeOperationalAttempt time.Time
becomeOperationalBackoff time.Duration
registered bool
reg chan struct{}
noRegister bool
preseed bool
preseedHybrid bool
preseedSystemLabel string
ntpSyncedOrTimedOut bool
onInit []StateDeviceInitialized
xkbConfigListener *keyboard.XKBConfigListener
}
// Manager returns a new device manager.
func Manager(s *state.State, hookManager *hookstate.HookManager, runner *state.TaskRunner, newStore func(storecontext.DeviceBackend) snapstate.StoreService) (*DeviceManager, error) {
delayedCrossMgrInit()
m := &DeviceManager{
state: s,
hookMgr: hookManager,
newStore: newStore,
reg: make(chan struct{}),
preseed: snapdenv.Preseeding(),
preseedHybrid: snapdenv.PreseedingHybrid(),
}
m.populateStateFromSeed = m.populateStateFromSeedImpl
if !m.preseed {
mode, explicit, err := boot.SystemMode("")
if err != nil {
return nil, err
}
if explicit {
logger.Debugf("explicitly set system mode")
m.sysMode = mode
}
} else {
// cache system label for preseeding of core20; note, this will fail on
// core16/core18 (they are not supported by preseeding) as core20 system
// label is expected.
if !release.OnClassic || m.preseedHybrid {
var err error
m.preseedSystemLabel, err = systemForPreseeding()
if err != nil {
return nil, err
}
m.sysMode = "run"
}
}
s.Lock()
s.Cache(deviceMgrKey{}, m)
s.Unlock()
if err := m.confirmRegistered(); err != nil {
return nil, err
}
hookManager.Register(regexp.MustCompile("^prepare-device$"), newBasicHookStateHandler)
hookManager.Register(regexp.MustCompile("^install-device$"), newBasicHookStateHandler)
hookManager.Register(regexp.MustCompile("^prepare-serial-request$"), newBasicHookStateHandler)
runner.AddHandler("generate-device-key", m.doGenerateDeviceKey, nil)
runner.AddHandler("request-serial", m.doRequestSerial, nil)
// Mark-preseeded touches and records the system-key, ensure that it does
// not run in parallel with other tasks touching the system-key
runner.AddHandler("mark-preseeded", m.doMarkPreseeded, nil)
runner.AddHandler("mark-seeded", m.doMarkSeeded, nil)
runner.AddHandler("setup-ubuntu-save", m.doSetupUbuntuSave, nil)
runner.AddHandler("setup-run-system", m.doSetupRunSystem, nil)
runner.AddHandler("factory-reset-run-system", m.doFactoryResetRunSystem, nil)
runner.AddHandler("restart-system-to-run-mode", m.doRestartSystemToRunMode, nil)
runner.AddHandler("prepare-remodeling", m.doPrepareRemodeling, nil)
runner.AddCleanup("prepare-remodeling", m.cleanupRemodel)
// this *must* always run last and finalizes a remodel
runner.AddHandler("set-model", m.doSetModel, nil)
runner.AddCleanup("set-model", m.cleanupRemodel)
// There is no undo for successful gadget updates. The system is
// rebooted during update, if it boots up to the point where snapd runs
// we deem the new assets (be it bootloader or firmware) functional. The
// deployed boot assets must be backward compatible with reverted kernel
// or gadget snaps. There are no further changes to the boot assets,
// unless a new gadget update is deployed.
runner.AddHandler("update-gadget-assets", m.doUpdateGadgetAssets, nil)
// There is no undo handler for successful boot config update. The
// config assets are assumed to be always backwards compatible.
runner.AddHandler("update-managed-boot-config", m.doUpdateManagedBootConfig, nil)
// kernel command line updates from a gadget supplied file
runner.AddHandler("update-gadget-cmdline", m.doUpdateGadgetCommandLine, m.undoUpdateGadgetCommandLine)
// recovery systems
runner.AddHandler("remove-recovery-system", m.doRemoveRecoverySystem, nil)
runner.AddHandler("create-recovery-system", m.doCreateRecoverySystem, m.undoCreateRecoverySystem)
runner.AddCleanup("create-recovery-system", m.cleanupRecoverySystem)
runner.AddHandler("finalize-recovery-system", m.doFinalizeTriedRecoverySystem, m.undoFinalizeTriedRecoverySystem)
runner.AddCleanup("finalize-recovery-system", m.cleanupRecoverySystem)
// used from the install API
// TODO: use better task names that are close to our usual pattern
runner.AddHandler("install-finish", m.doInstallFinish, nil)
runner.AddHandler("install-setup-storage-encryption", m.doInstallSetupStorageEncryption, nil)
runner.AddHandler("install-preseed", m.doInstallPreseed, nil)
runner.AddBlocked(gadgetUpdateBlocked)
runner.AddBlocked(removeRecoverySystemBlocked)
// wire FDE kernel hook support into boot
boot.HookKeyProtectorFactory = m.hookKeyProtectorFactory
hookManager.Register(regexp.MustCompile("^fde-setup$"), newFdeSetupHandler)
return m, nil
}
func ensureFileDirPermissions() error {
// Ensure the /var/lib/snapd/void dir has correct permissions, we
// do this in the postinst for classic systems already but it's
// needed here for Core systems.
st, err := os.Stat(dirs.SnapVoidDir)
if err == nil && st.Mode().Perm() != 0111 {
logger.Noticef("fixing permissions of %v to 0111", dirs.SnapVoidDir)
if err := os.Chmod(dirs.SnapVoidDir, 0111); err != nil {
return err
}
}
return nil
}
type genericHook struct{}
func (h genericHook) Before() error { return nil }
func (h genericHook) Done() error { return nil }
func (h genericHook) Error(err error) (bool, error) { return false, nil }
func newBasicHookStateHandler(context *hookstate.Context) hookstate.Handler {
return genericHook{}
}
// ReloadModeenv is only useful for integration testing
func (m *DeviceManager) ReloadModeenv() error {
osutil.MustBeTestBinary("ReloadModeenv can only be called from tests")
mode, explicit, err := boot.SystemMode("")
if err != nil {
return err
}
if explicit {
m.sysMode = mode
}
return nil
}
type SysExpectation int
const (
// SysAny indicates any system is appropriate.
SysAny SysExpectation = iota
// SysHasModeenv indicates only systems with modeenv are appropriate.
SysHasModeenv
)
func (m *DeviceManager) AddOnInit(onInit StateDeviceInitialized) {
m.onInit = append(m.onInit, onInit)
}
// SystemMode returns the current mode of the system.
// An expectation about the system controls the returned mode when
// none is set explicitly, as it's the case on pre-UC20 systems. In
// which case, with SysAny, the mode defaults to implicit "run", thus
// covering pre-UC20 systems. With SysHasModeeenv, as there is always
// an explicit mode in systems that use modeenv, no implicit default
// is used and thus "" is returned for pre-UC20 systems.
func (m *DeviceManager) SystemMode(sysExpect SysExpectation) string {
if m.sysMode == "" {
if sysExpect == SysHasModeenv {
return ""
}
return "run"
}
return m.sysMode
}
// StartUp implements StateStarterUp.Startup.
func (m *DeviceManager) StartUp() error {
err := func() error {
m.state.Lock()
defer m.state.Unlock()
dev, err := m.earlyDeviceContext()
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
// if ErrNoState then dev is nil, we assume a classic system here,
// any error will re-surface again in the main first boot code
if dev != nil && m.shouldMountUbuntuSave(dev) {
if err := m.setupUbuntuSave(dev); err != nil {
return fmt.Errorf("cannot set up ubuntu-save: %v", err)
}
}
// ensure /var/lib/snapd/void permissions are ok
if err := ensureFileDirPermissions(); err != nil {
logger.Noticef("%v", fmt.Errorf("cannot ensure device file/dir permissions: %v", err))
}
// TODO: setup proper timings measurements for this
return EarlyConfig(m.state, m.earlyPreloadGadget)
}()
if err != nil {
return err
}
for _, onInit := range m.onInit {
onInit.DeviceInitialized()
}
return nil
}
func (m *DeviceManager) Stop() {
if m.xkbConfigListener != nil {
m.xkbConfigListener.Close()
}
}
func (m *DeviceManager) shouldMountUbuntuSave(dev snap.Device) bool {
if dev.IsClassicBoot() {
return false
}
// TODO:UC20+: ubuntu-save needs to be mounted for recover too
return m.SystemMode(SysHasModeenv) == "run"
}
func (m *DeviceManager) ensureUbuntuSaveIsMounted() error {
saveMounted, err := osutil.IsMounted(dirs.SnapSaveDir)
if err != nil {
return err
}
if saveMounted {
logger.Noticef("save already mounted under %v", dirs.SnapSaveDir)
return nil
}
runMntSaveMounted, err := osutil.IsMounted(boot.InitramfsUbuntuSaveDir)
if err != nil {
return err
}
if !runMntSaveMounted {
// we don't have ubuntu-save, save will be used directly
logger.Noticef("no ubuntu-save mount")
return nil
}
sysd := systemd.New(systemd.SystemMode, progress.Null)
// In newer core20/core22 we have a mount unit for ubuntu-save, which we
// will try to start first. Invoking systemd-mount in this case would fail.
err = sysd.Start([]string{"var-lib-snapd-save.mount"})
if err == nil {
logger.Noticef("mount unit for ubuntu-save was started")
return nil
} else {
// We only fall through and mount directly if the failure was because of a missing
// mount file, which possible does not exist. Any other failure we treat as an actual
// error.
// XXX: systemd ideally should start returning some kind UnitNotFound errors in this situation
if !strings.Contains(err.Error(), "Unit var-lib-snapd-save.mount not found.") {
return err
}
}
// Otherwise try to directly mount the partition with systemd-mount.
logger.Noticef("bind-mounting ubuntu-save under %v", dirs.SnapSaveDir)
err = sysd.Mount(boot.InitramfsUbuntuSaveDir, dirs.SnapSaveDir, "-o", "bind")
if err != nil {
logger.Noticef("bind-mounting ubuntu-save failed %v", err)
return fmt.Errorf("cannot bind mount %v under %v: %v", boot.InitramfsUbuntuSaveDir, dirs.SnapSaveDir, err)
}
return nil
}
// ensureUbuntuSaveSnapFolders creates the necessary folder structure for
// /var/lib/snapd/save/snap/<snap>. This is normally done during installation
// of a snap, but there are two cases where this can be insufficient.
//
// 1. When migrating to a newer snapd, folders are not automatically created for
// snaps that are already installed. They will only be created during a refresh of
// the snap itself, whereas we want to cover all the cases.
// 2. During install mode for the gadget/kernel/etc, the folders are not created.
// So this function can be invoked as a part of system-setup.
func (m *DeviceManager) ensureUbuntuSaveSnapFolders() error {
snaps, err := snapstate.All(m.state)
if err != nil {
return err
}
for _, s := range snaps {
saveDir := snap.CommonDataSaveDir(s.InstanceName())
if err := os.MkdirAll(saveDir, 0755); err != nil {
return err
}
}
return nil
}
// setupUbuntuSave sets up ubuntu-save partition. It makes sure
// to mount ubuntu-save (if feasible), and ensures the correct snap
// folders are present according to currently installed snaps.
func (m *DeviceManager) setupUbuntuSave(dev snap.Device) error {
if err := m.ensureUbuntuSaveIsMounted(); err != nil {
return err
}
// At this point ubuntu-save should be available under the
// /var/lib/snapd/save path, so we mark the partition as such.
m.saveAvailable = true
// The last step is to ensure needed folder structure is present
// for the per-snap folder storage.
// We support this only on Core for now.
if dev.Classic() {
return nil
}
return m.ensureUbuntuSaveSnapFolders()
}
type deviceMgrKey struct{}
func deviceMgr(st *state.State) *DeviceManager {
mgr := st.Cached(deviceMgrKey{})
if mgr == nil {
panic("internal error: device manager is not yet associated with state")
}
return mgr.(*DeviceManager)
}
func (m *DeviceManager) CanStandby() bool {
var seeded bool
if err := m.state.Get("seeded", &seeded); err != nil {
return false
}
return seeded
}
func (m *DeviceManager) confirmRegistered() error {
m.state.Lock()
defer m.state.Unlock()
device, err := m.device()
if err != nil {
return err
}
if device.Serial != "" {
m.markRegistered()
}
return nil
}
func (m *DeviceManager) markRegistered() {
if m.registered {
return
}
m.registered = true
close(m.reg)
}
func gadgetUpdateBlocked(cand *state.Task, running []*state.Task) bool {
if cand.Kind() == "update-gadget-assets" && len(running) != 0 {
// update-gadget-assets must be the only task running
return true
}
for _, other := range running {
if other.Kind() == "update-gadget-assets" {
// no other task can be started when
// update-gadget-assets is running
return true
}
}
return false
}
func removeRecoverySystemBlocked(cand *state.Task, running []*state.Task) bool {
// remove-recovery-system computes task-local cleanup state that depends on
// the current set of recovery systems before dropping the state lock, so
// always keep these tasks serialized
if cand.Kind() != "remove-recovery-system" {
return false
}
for _, other := range running {
if other.Kind() == "remove-recovery-system" {
return true
}
}
return false
}
func (m *DeviceManager) changeInFlight(kind string) bool {
for _, chg := range m.state.Changes() {
if chg.Kind() == kind && !chg.IsReady() {
// change already in motion
return true
}
}
return false
}
// helpers to keep count of attempts to get a serial, useful to decide
// to give up holding off trying to auto-refresh
type ensureOperationalAttemptsKey struct{}
func incEnsureOperationalAttempts(st *state.State) {
cur, _ := st.Cached(ensureOperationalAttemptsKey{}).(int)
st.Cache(ensureOperationalAttemptsKey{}, cur+1)
}
func ensureOperationalAttempts(st *state.State) int {
cur, _ := st.Cached(ensureOperationalAttemptsKey{}).(int)
return cur
}
// ensureOperationalShouldBackoff returns whether we should abstain from
// further become-operational tentatives while its backoff interval is
// not expired.
func (m *DeviceManager) ensureOperationalShouldBackoff(now time.Time) bool {
if !m.lastBecomeOperationalAttempt.IsZero() && m.lastBecomeOperationalAttempt.Add(m.becomeOperationalBackoff).After(now) {
return true
}
if m.becomeOperationalBackoff == 0 {
m.becomeOperationalBackoff = 5 * time.Minute
} else {
newBackoff := m.becomeOperationalBackoff * 2
if newBackoff > (12 * time.Hour) {
newBackoff = 24 * time.Hour
}
m.becomeOperationalBackoff = newBackoff
}
m.lastBecomeOperationalAttempt = now
return false
}
func setClassicFallbackModel(st *state.State, device *auth.DeviceState) error {
err := assertstate.Add(st, sysdb.GenericClassicModel())
if err != nil && !asserts.IsUnaccceptedUpdate(err) {
return fmt.Errorf(`cannot install "generic-classic" fallback model assertion: %v`, err)
}
device.Brand = "generic"
device.Model = "generic-classic"
if err := internal.SetDevice(st, device); err != nil {
return err
}
return nil
}
func (m *DeviceManager) ensureOperational() error {
m.state.Lock()
defer m.state.Unlock()
if m.SystemMode(SysAny) != "run" {
// avoid doing registration in ephemeral mode
// note: this also stop auto-refreshes indirectly
return nil
}
device, err := m.device()
if err != nil {
return err
}
if device.Serial != "" {
// serial is set, we are all set
return nil
}
logger.Trace("ensure", "manager", "DeviceManager", "func", "ensureOperational")
perfTimings := timings.New(map[string]string{"ensure": "become-operational"})
// conditions to trigger device registration
//
// * have a model assertion with a gadget (core and
// device-like classic) in which case we need also to wait
// for the gadget to have been installed though
// TODO: consider a way to support lazy registration on classic
// even with a gadget and some preseeded snaps
//
// * classic with a model assertion with a non-default store specified
// * lazy classic case (might have a model with no gadget nor store
// or no model): we wait to have some snaps installed or be
// in the process to install some
var seeded bool
err = m.state.Get("seeded", &seeded)
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if device.Brand == "" || device.Model == "" {
if !release.OnClassic || !seeded {
return nil
}
// we are on classic and seeded but there is no model:
// use a fallback model!
err := setClassicFallbackModel(m.state, device)
if err != nil {
return err
}
}
if m.noRegister {
return nil
}
// noregister marker file is checked below after mostly in-memory checks
if m.changeInFlight("become-operational") {
return nil
}
var storeID, gadget string
model, err := m.Model()
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if err == nil {
gadget = model.Gadget()
storeID = model.Store()
} else {
return fmt.Errorf("internal error: core device brand and model are set but there is no model assertion")
}
willRequestSerial, err := shouldRequestSerial(m.state, gadget)
if err != nil {
return err
}
// if we should not fetch the device serial (either store.access or
// device.service.access is set to offline), and we have already generated a
// device key, we can return early. otherwise, we need to run the
// generate-device-key task
if !willRequestSerial && device.KeyID != "" {
return nil
}
if gadget == "" && storeID == "" {
// classic: if we have no gadget and no non-default store
// wait to have snaps or snap installation
n, err := snapstate.NumSnaps(m.state)
if err != nil {
return err
}
if n == 0 && !snapstate.Installing(m.state) {
return nil
}
}
// registration is blocked until reboot
if osutil.FileExists(filepath.Join(dirs.SnapRunDir, "noregister")) {
m.noRegister = true
return nil
}
var hasPrepareDeviceHook bool
// if there's a gadget specified wait for it
if gadget != "" {
// if have a gadget wait until seeded to proceed
if !seeded {
// this will be run again, so eventually when the system is
// seeded the code below runs
return nil
}
gadgetInfo, err := snapstate.CurrentInfo(m.state, gadget)
if err != nil {
return err
}
hasPrepareDeviceHook = (gadgetInfo.Hooks["prepare-device"] != nil)
}
if device.KeyID == "" && model.Grade() != "" {
// UC20+ devices support factory reset
serial, err := m.maybeRestoreAfterReset(device)
if err != nil {
return err
}
if serial != nil {
device.KeyID = serial.DeviceKey().ID()
device.Serial = serial.Serial()
if err := m.setDevice(device); err != nil {
return fmt.Errorf("cannot set device for restored serial and key: %v", err)
}
logger.Noticef("restored serial %v for %v/%v signed with key %v",
device.Serial, device.Brand, device.Model, device.KeyID)
return nil
}
}
// have some backoff between full retries
if m.ensureOperationalShouldBackoff(time.Now()) {
return nil
}
// increment attempt count
incEnsureOperationalAttempts(m.state)
// XXX: some of these will need to be split and use hooks
// retries might need to embrace more than one "task" then,
// need to be careful
tasks := []*state.Task{}
var prepareDevice *state.Task
if hasPrepareDeviceHook {
summary := i18n.G("Run prepare-device hook")
hooksup := &hookstate.HookSetup{
Snap: gadget,
Hook: "prepare-device",
}
prepareDevice = hookstate.HookTask(m.state, summary, hooksup, nil)
tasks = append(tasks, prepareDevice)
}
genKey := m.state.NewTask("generate-device-key", i18n.G("Generate device key"))
if prepareDevice != nil {
genKey.WaitFor(prepareDevice)
}
tasks = append(tasks, genKey)
if willRequestSerial {
requestSerial := m.state.NewTask("request-serial", i18n.G("Request device serial"))
requestSerial.WaitFor(genKey)
tasks = append(tasks, requestSerial)
}
chg := m.state.NewChange(becomeOperationalChangeKind, i18n.G("Initialize device"))
chg.AddAll(state.NewTaskSet(tasks...))
state.TagTimingsWithChange(perfTimings, chg)
perfTimings.Save(m.state)
return nil
}
// maybeRestoreAfterReset attempts to restore the serial assertion with a
// matching key in a post-factory reset scenario. It is possible that it is
// called when the device was unregistered, but when doing so, the device key is
// removed.
func (m *DeviceManager) maybeRestoreAfterReset(device *auth.DeviceState) (*asserts.Serial, error) {
// there should be a serial assertion for the current model
serials, err := assertstate.DB(m.state).FindMany(asserts.SerialType, map[string]string{
"brand-id": device.Brand,
"model": device.Model,
})
if err != nil {
if errors.Is(err, &asserts.NotFoundError{}) {
// no serial assertion
return nil, nil
}
return nil, err
}
for _, serial := range serials {
serialAs := serial.(*asserts.Serial)
deviceKeyID := serialAs.DeviceKey().ID()
logger.Debugf("processing candidate serial assertion for %v/%v signed with key %v",
device.Brand, device.Model, deviceKeyID)
// serial assertion is signed with the device key, its ID is in
// the header; factory-reset would have restored the serial
// assertion and a matching device key, OTOH when the device is
// unregistered we explicitly remove the key, hence should this
// code process such serial assertion, there will be no matching
// key for it
err = m.withKeypairMgr(func(kpmgr asserts.KeypairManager) error {
_, err := kpmgr.Get(deviceKeyID)
return err
})
if err != nil {
if asserts.IsKeyNotFound(err) {
// there is no key matching this serial assertion,
// perhaps device was unregistered at some point
continue
}
return nil, err
}
return serialAs, nil
}
// none of the assertions has a matching key
return nil, nil
}
var startTime time.Time
func init() {
startTime = time.Now()
}
func (m *DeviceManager) setTimeOnce(name string, t time.Time) error {
var prev time.Time
err := m.state.Get(name, &prev)
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if !prev.IsZero() {
// already set
return nil
}
m.state.Set(name, t)
return nil
}
func (m *DeviceManager) seedStart() (*timings.Timings, error) {
if m.seedTimings != nil {
// reuse the early cached one
return m.seedTimings, nil
}
perfTimings := timings.New(map[string]string{"ensure": "seed"})
var recordedStart string
var start time.Time
if m.preseed {
recordedStart = "preseed-start-time"
start = timeNow()
} else {
recordedStart = "seed-start-time"
start = startTime
}
if err := m.setTimeOnce(recordedStart, start); err != nil {
return nil, err
}
return perfTimings, nil
}
func (m *DeviceManager) systemForPreseeding() string {
if m.preseedSystemLabel == "" {
panic("no system to preseed")
}
return m.preseedSystemLabel
}
func (m *DeviceManager) earlyDeviceContext() (snapstate.DeviceContext, error) {
mod, err := findModel(m.state)
if err == nil {
return newModelDeviceContext(m, mod), nil
}
if !errors.Is(err, state.ErrNoState) {
return nil, err
}
dev, _, err := m.earlyLoadDeviceSeed(state.ErrNoState)
return dev, err
}
// seedLabelAndMode finds out the label and mode under which to seed the system.
// Only to use if not yet seeded.
// TODO: can it be unified with the code in Manager?
func (m *DeviceManager) seedLabelAndMode() (seedLabel, seedMode string, err error) {
if m.seedChosen {
return m.seedLabel, m.seedMode, nil
}
if m.preseed {
if !release.OnClassic || m.preseedHybrid {
seedMode = "run"
seedLabel = m.systemForPreseeding()
}
} else {
modeenv, err := boot.MaybeReadModeenv()
if err != nil {
return "", "", err
}
if modeenv != nil {
logger.Debugf("modeenv read, mode %q label %q",
modeenv.Mode, modeenv.RecoverySystem)
seedMode = modeenv.Mode
seedLabel = modeenv.RecoverySystem
}
}
m.seedLabel = seedLabel
m.seedMode = seedMode
m.seedChosen = true
return seedLabel, seedMode, nil
}
func (m *DeviceManager) earlyLoadDeviceSeed(seedLoadErr error) (snapstate.DeviceContext, seed.Seed, error) {
var seeded bool
err := m.state.Get("seeded", &seeded)
if err != nil && !errors.Is(err, state.ErrNoState) {
return nil, nil, err
}
if seeded {
return nil, nil, fmt.Errorf("internal error: loading device seed after being seeded already")
}
// consider whether we were called already
if m.earlyDeviceSeed != nil {
return newModelDeviceContext(m, m.earlyDeviceSeed.Model()), m.earlyDeviceSeed, nil
}
sysLabel, _, err := m.seedLabelAndMode()