github.com/bugraaydogar/snapd@v0.0.0-20210315170335-8c70bb858939/overlord/devicestate/devicemgr.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2016-2021 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package devicestate
    21  
    22  import (
    23  	"context"
    24  	"encoding/json"
    25  	"errors"
    26  	"fmt"
    27  	"os"
    28  	"path/filepath"
    29  	"regexp"
    30  	"strings"
    31  	"time"
    32  
    33  	"github.com/snapcore/snapd/asserts"
    34  	"github.com/snapcore/snapd/asserts/sysdb"
    35  	"github.com/snapcore/snapd/boot"
    36  	"github.com/snapcore/snapd/dirs"
    37  	"github.com/snapcore/snapd/gadget"
    38  	"github.com/snapcore/snapd/i18n"
    39  	"github.com/snapcore/snapd/logger"
    40  	"github.com/snapcore/snapd/osutil"
    41  	"github.com/snapcore/snapd/overlord/assertstate"
    42  	"github.com/snapcore/snapd/overlord/auth"
    43  	"github.com/snapcore/snapd/overlord/configstate/config"
    44  	"github.com/snapcore/snapd/overlord/devicestate/fde"
    45  	"github.com/snapcore/snapd/overlord/devicestate/internal"
    46  	"github.com/snapcore/snapd/overlord/hookstate"
    47  	"github.com/snapcore/snapd/overlord/snapstate"
    48  	"github.com/snapcore/snapd/overlord/state"
    49  	"github.com/snapcore/snapd/overlord/storecontext"
    50  	"github.com/snapcore/snapd/progress"
    51  	"github.com/snapcore/snapd/release"
    52  	"github.com/snapcore/snapd/seed"
    53  	"github.com/snapcore/snapd/snap"
    54  	"github.com/snapcore/snapd/snap/snapfile"
    55  	"github.com/snapcore/snapd/snapdenv"
    56  	"github.com/snapcore/snapd/sysconfig"
    57  	"github.com/snapcore/snapd/systemd"
    58  	"github.com/snapcore/snapd/timings"
    59  )
    60  
    61  var (
    62  	cloudInitStatus   = sysconfig.CloudInitStatus
    63  	restrictCloudInit = sysconfig.RestrictCloudInit
    64  )
    65  
    66  // EarlyConfig is a hook set by configstate that can process early configuration
    67  // during managers' startup.
    68  var EarlyConfig func(st *state.State, preloadGadget func() (*gadget.Info, error)) error
    69  
    70  // DeviceManager is responsible for managing the device identity and device
    71  // policies.
    72  type DeviceManager struct {
    73  	systemMode string
    74  	// saveAvailable keeps track whether /var/lib/snapd/save
    75  	// is available, i.e. exists and is mounted from ubuntu-save
    76  	// if the latter exists.
    77  	// TODO: evolve this to state to track things if we start mounting
    78  	// save as rw vs ro, or mount/umount it fully on demand
    79  	saveAvailable bool
    80  
    81  	state   *state.State
    82  	hookMgr *hookstate.HookManager
    83  
    84  	cachedKeypairMgr asserts.KeypairManager
    85  
    86  	// newStore can make new stores for remodeling
    87  	newStore func(storecontext.DeviceBackend) snapstate.StoreService
    88  
    89  	bootOkRan            bool
    90  	bootRevisionsUpdated bool
    91  
    92  	seedTimings *timings.Timings
    93  
    94  	ensureSeedInConfigRan bool
    95  
    96  	ensureInstalledRan bool
    97  
    98  	cloudInitAlreadyRestricted           bool
    99  	cloudInitErrorAttemptStart           *time.Time
   100  	cloudInitEnabledInactiveAttemptStart *time.Time
   101  
   102  	lastBecomeOperationalAttempt time.Time
   103  	becomeOperationalBackoff     time.Duration
   104  	registered                   bool
   105  	reg                          chan struct{}
   106  
   107  	preseed bool
   108  }
   109  
   110  // Manager returns a new device manager.
   111  func Manager(s *state.State, hookManager *hookstate.HookManager, runner *state.TaskRunner, newStore func(storecontext.DeviceBackend) snapstate.StoreService) (*DeviceManager, error) {
   112  	delayedCrossMgrInit()
   113  
   114  	m := &DeviceManager{
   115  		state:    s,
   116  		hookMgr:  hookManager,
   117  		newStore: newStore,
   118  		reg:      make(chan struct{}),
   119  		preseed:  snapdenv.Preseeding(),
   120  	}
   121  
   122  	modeEnv, err := maybeReadModeenv()
   123  	if err != nil {
   124  		return nil, err
   125  	}
   126  	if modeEnv != nil {
   127  		m.systemMode = modeEnv.Mode
   128  	}
   129  
   130  	s.Lock()
   131  	s.Cache(deviceMgrKey{}, m)
   132  	s.Unlock()
   133  
   134  	if err := m.confirmRegistered(); err != nil {
   135  		return nil, err
   136  	}
   137  
   138  	hookManager.Register(regexp.MustCompile("^prepare-device$"), newPrepareDeviceHandler)
   139  
   140  	runner.AddHandler("generate-device-key", m.doGenerateDeviceKey, nil)
   141  	runner.AddHandler("request-serial", m.doRequestSerial, nil)
   142  	runner.AddHandler("mark-preseeded", m.doMarkPreseeded, nil)
   143  	runner.AddHandler("mark-seeded", m.doMarkSeeded, nil)
   144  	runner.AddHandler("setup-run-system", m.doSetupRunSystem, nil)
   145  	runner.AddHandler("prepare-remodeling", m.doPrepareRemodeling, nil)
   146  	runner.AddCleanup("prepare-remodeling", m.cleanupRemodel)
   147  	// this *must* always run last and finalizes a remodel
   148  	runner.AddHandler("set-model", m.doSetModel, nil)
   149  	runner.AddCleanup("set-model", m.cleanupRemodel)
   150  	// There is no undo for successful gadget updates. The system is
   151  	// rebooted during update, if it boots up to the point where snapd runs
   152  	// we deem the new assets (be it bootloader or firmware) functional. The
   153  	// deployed boot assets must be backward compatible with reverted kernel
   154  	// or gadget snaps. There are no further changes to the boot assets,
   155  	// unless a new gadget update is deployed.
   156  	runner.AddHandler("update-gadget-assets", m.doUpdateGadgetAssets, nil)
   157  	// There is no undo handler for successful boot config update. The
   158  	// config assets are assumed to be always backwards compatible.
   159  	runner.AddHandler("update-managed-boot-config", m.doUpdateManagedBootConfig, nil)
   160  
   161  	runner.AddBlocked(gadgetUpdateBlocked)
   162  
   163  	// wire FDE kernel hook support into boot
   164  	boot.HasFDESetupHook = m.hasFDESetupHook
   165  	boot.RunFDESetupHook = m.runFDESetupHook
   166  	hookManager.Register(regexp.MustCompile("^fde-setup$"), newFdeSetupHandler)
   167  
   168  	return m, nil
   169  }
   170  
   171  func maybeReadModeenv() (*boot.Modeenv, error) {
   172  	modeEnv, err := boot.ReadModeenv("")
   173  	if err != nil && !os.IsNotExist(err) {
   174  		return nil, fmt.Errorf("cannot read modeenv: %v", err)
   175  	}
   176  	return modeEnv, nil
   177  }
   178  
   179  // StartUp implements StateStarterUp.Startup.
   180  func (m *DeviceManager) StartUp() error {
   181  	// system mode is explicitly set on UC20
   182  	// TODO:UC20: ubuntu-save needs to be mounted for recover too
   183  	if !release.OnClassic && m.systemMode == "run" {
   184  		if err := m.maybeSetupUbuntuSave(); err != nil {
   185  			return fmt.Errorf("cannot set up ubuntu-save: %v", err)
   186  		}
   187  	}
   188  
   189  	// TODO: setup proper timings measurements for this
   190  
   191  	m.state.Lock()
   192  	defer m.state.Unlock()
   193  	return EarlyConfig(m.state, m.preloadGadget)
   194  }
   195  
   196  func (m *DeviceManager) maybeSetupUbuntuSave() error {
   197  	// only called for UC20
   198  
   199  	saveMounted, err := osutil.IsMounted(dirs.SnapSaveDir)
   200  	if err != nil {
   201  		return err
   202  	}
   203  	if saveMounted {
   204  		logger.Noticef("save already mounted under %v", dirs.SnapSaveDir)
   205  		m.saveAvailable = true
   206  		return nil
   207  	}
   208  
   209  	runMntSaveMounted, err := osutil.IsMounted(boot.InitramfsUbuntuSaveDir)
   210  	if err != nil {
   211  		return err
   212  	}
   213  	if !runMntSaveMounted {
   214  		// we don't have ubuntu-save, save will be used directly
   215  		logger.Noticef("no ubuntu-save mount")
   216  		m.saveAvailable = true
   217  		return nil
   218  	}
   219  
   220  	logger.Noticef("bind-mounting ubuntu-save under %v", dirs.SnapSaveDir)
   221  
   222  	err = systemd.New(systemd.SystemMode, progress.Null).Mount(boot.InitramfsUbuntuSaveDir,
   223  		dirs.SnapSaveDir, "-o", "bind")
   224  	if err != nil {
   225  		logger.Noticef("bind-mounting ubuntu-save failed %v", err)
   226  		return fmt.Errorf("cannot bind mount %v under %v: %v", boot.InitramfsUbuntuSaveDir, dirs.SnapSaveDir, err)
   227  	}
   228  	m.saveAvailable = true
   229  	return nil
   230  }
   231  
   232  type deviceMgrKey struct{}
   233  
   234  func deviceMgr(st *state.State) *DeviceManager {
   235  	mgr := st.Cached(deviceMgrKey{})
   236  	if mgr == nil {
   237  		panic("internal error: device manager is not yet associated with state")
   238  	}
   239  	return mgr.(*DeviceManager)
   240  }
   241  
   242  func (m *DeviceManager) CanStandby() bool {
   243  	var seeded bool
   244  	if err := m.state.Get("seeded", &seeded); err != nil {
   245  		return false
   246  	}
   247  	return seeded
   248  }
   249  
   250  func (m *DeviceManager) confirmRegistered() error {
   251  	m.state.Lock()
   252  	defer m.state.Unlock()
   253  
   254  	device, err := m.device()
   255  	if err != nil {
   256  		return err
   257  	}
   258  
   259  	if device.Serial != "" {
   260  		m.markRegistered()
   261  	}
   262  	return nil
   263  }
   264  
   265  func (m *DeviceManager) markRegistered() {
   266  	if m.registered {
   267  		return
   268  	}
   269  	m.registered = true
   270  	close(m.reg)
   271  }
   272  
   273  func gadgetUpdateBlocked(cand *state.Task, running []*state.Task) bool {
   274  	if cand.Kind() == "update-gadget-assets" && len(running) != 0 {
   275  		// update-gadget-assets must be the only task running
   276  		return true
   277  	} else {
   278  		for _, other := range running {
   279  			if other.Kind() == "update-gadget-assets" {
   280  				// no other task can be started when
   281  				// update-gadget-assets is running
   282  				return true
   283  			}
   284  		}
   285  	}
   286  
   287  	return false
   288  }
   289  
   290  type prepareDeviceHandler struct{}
   291  
   292  func newPrepareDeviceHandler(context *hookstate.Context) hookstate.Handler {
   293  	return prepareDeviceHandler{}
   294  }
   295  
   296  func (h prepareDeviceHandler) Before() error {
   297  	return nil
   298  }
   299  
   300  func (h prepareDeviceHandler) Done() error {
   301  	return nil
   302  }
   303  
   304  func (h prepareDeviceHandler) Error(err error) error {
   305  	return nil
   306  }
   307  
   308  func (m *DeviceManager) changeInFlight(kind string) bool {
   309  	for _, chg := range m.state.Changes() {
   310  		if chg.Kind() == kind && !chg.Status().Ready() {
   311  			// change already in motion
   312  			return true
   313  		}
   314  	}
   315  	return false
   316  }
   317  
   318  // helpers to keep count of attempts to get a serial, useful to decide
   319  // to give up holding off trying to auto-refresh
   320  
   321  type ensureOperationalAttemptsKey struct{}
   322  
   323  func incEnsureOperationalAttempts(st *state.State) {
   324  	cur, _ := st.Cached(ensureOperationalAttemptsKey{}).(int)
   325  	st.Cache(ensureOperationalAttemptsKey{}, cur+1)
   326  }
   327  
   328  func ensureOperationalAttempts(st *state.State) int {
   329  	cur, _ := st.Cached(ensureOperationalAttemptsKey{}).(int)
   330  	return cur
   331  }
   332  
   333  // ensureOperationalShouldBackoff returns whether we should abstain from
   334  // further become-operational tentatives while its backoff interval is
   335  // not expired.
   336  func (m *DeviceManager) ensureOperationalShouldBackoff(now time.Time) bool {
   337  	if !m.lastBecomeOperationalAttempt.IsZero() && m.lastBecomeOperationalAttempt.Add(m.becomeOperationalBackoff).After(now) {
   338  		return true
   339  	}
   340  	if m.becomeOperationalBackoff == 0 {
   341  		m.becomeOperationalBackoff = 5 * time.Minute
   342  	} else {
   343  		newBackoff := m.becomeOperationalBackoff * 2
   344  		if newBackoff > (12 * time.Hour) {
   345  			newBackoff = 24 * time.Hour
   346  		}
   347  		m.becomeOperationalBackoff = newBackoff
   348  	}
   349  	m.lastBecomeOperationalAttempt = now
   350  	return false
   351  }
   352  
   353  func setClassicFallbackModel(st *state.State, device *auth.DeviceState) error {
   354  	err := assertstate.Add(st, sysdb.GenericClassicModel())
   355  	if err != nil && !asserts.IsUnaccceptedUpdate(err) {
   356  		return fmt.Errorf(`cannot install "generic-classic" fallback model assertion: %v`, err)
   357  	}
   358  	device.Brand = "generic"
   359  	device.Model = "generic-classic"
   360  	if err := internal.SetDevice(st, device); err != nil {
   361  		return err
   362  	}
   363  	return nil
   364  }
   365  
   366  func (m *DeviceManager) SystemMode() string {
   367  	if m.systemMode == "" {
   368  		return "run"
   369  	}
   370  	return m.systemMode
   371  }
   372  
   373  func (m *DeviceManager) ensureOperational() error {
   374  	m.state.Lock()
   375  	defer m.state.Unlock()
   376  
   377  	if m.SystemMode() != "run" {
   378  		// avoid doing registration in ephemeral mode
   379  		// note: this also stop auto-refreshes indirectly
   380  		return nil
   381  	}
   382  
   383  	device, err := m.device()
   384  	if err != nil {
   385  		return err
   386  	}
   387  
   388  	if device.Serial != "" {
   389  		// serial is set, we are all set
   390  		return nil
   391  	}
   392  
   393  	perfTimings := timings.New(map[string]string{"ensure": "become-operational"})
   394  
   395  	// conditions to trigger device registration
   396  	//
   397  	// * have a model assertion with a gadget (core and
   398  	//   device-like classic) in which case we need also to wait
   399  	//   for the gadget to have been installed though
   400  	// TODO: consider a way to support lazy registration on classic
   401  	// even with a gadget and some preseeded snaps
   402  	//
   403  	// * classic with a model assertion with a non-default store specified
   404  	// * lazy classic case (might have a model with no gadget nor store
   405  	//   or no model): we wait to have some snaps installed or be
   406  	//   in the process to install some
   407  
   408  	var seeded bool
   409  	err = m.state.Get("seeded", &seeded)
   410  	if err != nil && err != state.ErrNoState {
   411  		return err
   412  	}
   413  
   414  	if device.Brand == "" || device.Model == "" {
   415  		if !release.OnClassic || !seeded {
   416  			return nil
   417  		}
   418  		// we are on classic and seeded but there is no model:
   419  		// use a fallback model!
   420  		err := setClassicFallbackModel(m.state, device)
   421  		if err != nil {
   422  			return err
   423  		}
   424  	}
   425  
   426  	if m.changeInFlight("become-operational") {
   427  		return nil
   428  	}
   429  
   430  	var storeID, gadget string
   431  	model, err := m.Model()
   432  	if err != nil && err != state.ErrNoState {
   433  		return err
   434  	}
   435  	if err == nil {
   436  		gadget = model.Gadget()
   437  		storeID = model.Store()
   438  	} else {
   439  		return fmt.Errorf("internal error: core device brand and model are set but there is no model assertion")
   440  	}
   441  
   442  	if gadget == "" && storeID == "" {
   443  		// classic: if we have no gadget and no non-default store
   444  		// wait to have snaps or snap installation
   445  
   446  		n, err := snapstate.NumSnaps(m.state)
   447  		if err != nil {
   448  			return err
   449  		}
   450  		if n == 0 && !snapstate.Installing(m.state) {
   451  			return nil
   452  		}
   453  	}
   454  
   455  	var hasPrepareDeviceHook bool
   456  	// if there's a gadget specified wait for it
   457  	if gadget != "" {
   458  		// if have a gadget wait until seeded to proceed
   459  		if !seeded {
   460  			// this will be run again, so eventually when the system is
   461  			// seeded the code below runs
   462  			return nil
   463  
   464  		}
   465  
   466  		gadgetInfo, err := snapstate.CurrentInfo(m.state, gadget)
   467  		if err != nil {
   468  			return err
   469  		}
   470  		hasPrepareDeviceHook = (gadgetInfo.Hooks["prepare-device"] != nil)
   471  	}
   472  
   473  	// have some backoff between full retries
   474  	if m.ensureOperationalShouldBackoff(time.Now()) {
   475  		return nil
   476  	}
   477  	// increment attempt count
   478  	incEnsureOperationalAttempts(m.state)
   479  
   480  	// XXX: some of these will need to be split and use hooks
   481  	// retries might need to embrace more than one "task" then,
   482  	// need to be careful
   483  
   484  	tasks := []*state.Task{}
   485  
   486  	var prepareDevice *state.Task
   487  	if hasPrepareDeviceHook {
   488  		summary := i18n.G("Run prepare-device hook")
   489  		hooksup := &hookstate.HookSetup{
   490  			Snap: gadget,
   491  			Hook: "prepare-device",
   492  		}
   493  		prepareDevice = hookstate.HookTask(m.state, summary, hooksup, nil)
   494  		tasks = append(tasks, prepareDevice)
   495  		// hooks are under a different manager, make sure we consider
   496  		// it immediately
   497  		m.state.EnsureBefore(0)
   498  	}
   499  
   500  	genKey := m.state.NewTask("generate-device-key", i18n.G("Generate device key"))
   501  	if prepareDevice != nil {
   502  		genKey.WaitFor(prepareDevice)
   503  	}
   504  	tasks = append(tasks, genKey)
   505  	requestSerial := m.state.NewTask("request-serial", i18n.G("Request device serial"))
   506  	requestSerial.WaitFor(genKey)
   507  	tasks = append(tasks, requestSerial)
   508  
   509  	chg := m.state.NewChange("become-operational", i18n.G("Initialize device"))
   510  	chg.AddAll(state.NewTaskSet(tasks...))
   511  
   512  	state.TagTimingsWithChange(perfTimings, chg)
   513  	perfTimings.Save(m.state)
   514  
   515  	return nil
   516  }
   517  
   518  var startTime time.Time
   519  
   520  func init() {
   521  	startTime = time.Now()
   522  }
   523  
   524  func (m *DeviceManager) setTimeOnce(name string, t time.Time) error {
   525  	var prev time.Time
   526  	err := m.state.Get(name, &prev)
   527  	if err != nil && err != state.ErrNoState {
   528  		return err
   529  	}
   530  	if !prev.IsZero() {
   531  		// already set
   532  		return nil
   533  	}
   534  	m.state.Set(name, t)
   535  	return nil
   536  }
   537  
   538  func (m *DeviceManager) seedStart() (*timings.Timings, error) {
   539  	if m.seedTimings != nil {
   540  		// reuse the early cached one
   541  		return m.seedTimings, nil
   542  	}
   543  	perfTimings := timings.New(map[string]string{"ensure": "seed"})
   544  
   545  	var recordedStart string
   546  	var start time.Time
   547  	if m.preseed {
   548  		recordedStart = "preseed-start-time"
   549  		start = timeNow()
   550  	} else {
   551  		recordedStart = "seed-start-time"
   552  		start = startTime
   553  	}
   554  	if err := m.setTimeOnce(recordedStart, start); err != nil {
   555  		return nil, err
   556  	}
   557  	return perfTimings, nil
   558  }
   559  
   560  func (m *DeviceManager) preloadGadget() (*gadget.Info, error) {
   561  	var sysLabel string
   562  	modeEnv, err := maybeReadModeenv()
   563  	if err != nil {
   564  		return nil, err
   565  	}
   566  	if modeEnv != nil {
   567  		sysLabel = modeEnv.RecoverySystem
   568  	}
   569  
   570  	// we time preloadGadget + first ensureSeeded together
   571  	// under --ensure=seed
   572  	tm, err := m.seedStart()
   573  	if err != nil {
   574  		return nil, err
   575  	}
   576  	// cached for first ensureSeeded
   577  	m.seedTimings = tm
   578  
   579  	// Here we behave as if there was no gadget if we encounter
   580  	// errors, under the assumption that those will be resurfaced
   581  	// in ensureSeed. This preserves having a failing to seed
   582  	// snapd continuing running.
   583  	//
   584  	// TODO: consider changing that again but we need consider the
   585  	// effect of the different failure mode.
   586  	//
   587  	// We also assume that anything sensitive will not be guarded
   588  	// just by option flags. For example automatic user creation
   589  	// also requires the model to be known/set. Otherwise ignoring
   590  	// errors here would be problematic.
   591  	var deviceSeed seed.Seed
   592  	timings.Run(tm, "import-assertions[early]", "early import assertions from seed", func(nested timings.Measurer) {
   593  		deviceSeed, err = loadDeviceSeed(m.state, sysLabel)
   594  	})
   595  	if err != nil {
   596  		// this same error will be resurfaced in ensureSeed later
   597  		if err != seed.ErrNoAssertions {
   598  			logger.Debugf("early import assertions from seed failed: %v", err)
   599  		}
   600  		return nil, state.ErrNoState
   601  	}
   602  	model := deviceSeed.Model()
   603  	if model.Gadget() == "" {
   604  		// no gadget
   605  		return nil, state.ErrNoState
   606  	}
   607  	var gi *gadget.Info
   608  	timings.Run(tm, "preload-verified-gadget-metadata", "preload verified gadget metadata from seed", func(nested timings.Measurer) {
   609  		gi, err = func() (*gadget.Info, error) {
   610  			if err := deviceSeed.LoadEssentialMeta([]snap.Type{snap.TypeGadget}, nested); err != nil {
   611  				return nil, err
   612  			}
   613  			essGadget := deviceSeed.EssentialSnaps()
   614  			if len(essGadget) != 1 {
   615  				return nil, fmt.Errorf("multiple gadgets among essential snaps are unexpected")
   616  			}
   617  			snapf, err := snapfile.Open(essGadget[0].Path)
   618  			if err != nil {
   619  				return nil, err
   620  			}
   621  			return gadget.ReadInfoFromSnapFile(snapf, model)
   622  		}()
   623  	})
   624  	if err != nil {
   625  		logger.Noticef("preload verified gadget metadata from seed failed: %v", err)
   626  		return nil, state.ErrNoState
   627  	}
   628  	return gi, nil
   629  }
   630  
   631  var populateStateFromSeed = populateStateFromSeedImpl
   632  
   633  // ensureSeeded makes sure that the snaps from seed.yaml get installed
   634  // with the matching assertions
   635  func (m *DeviceManager) ensureSeeded() error {
   636  	m.state.Lock()
   637  	defer m.state.Unlock()
   638  
   639  	var seeded bool
   640  	err := m.state.Get("seeded", &seeded)
   641  	if err != nil && err != state.ErrNoState {
   642  		return err
   643  	}
   644  	if seeded {
   645  		return nil
   646  	}
   647  
   648  	if m.changeInFlight("seed") {
   649  		return nil
   650  	}
   651  
   652  	perfTimings, err := m.seedStart()
   653  	if err != nil {
   654  		return err
   655  	}
   656  	// we time preloadGadget + first ensureSeeded together
   657  	// succcessive ensureSeeded should be timed separately
   658  	m.seedTimings = nil
   659  
   660  	var opts *populateStateFromSeedOptions
   661  	if m.preseed {
   662  		opts = &populateStateFromSeedOptions{Preseed: true}
   663  	} else {
   664  		modeEnv, err := maybeReadModeenv()
   665  		if err != nil {
   666  			return err
   667  		}
   668  		if modeEnv != nil {
   669  			opts = &populateStateFromSeedOptions{
   670  				Mode:  m.systemMode,
   671  				Label: modeEnv.RecoverySystem,
   672  			}
   673  		}
   674  	}
   675  
   676  	var tsAll []*state.TaskSet
   677  	timings.Run(perfTimings, "state-from-seed", "populate state from seed", func(tm timings.Measurer) {
   678  		tsAll, err = populateStateFromSeed(m.state, opts, tm)
   679  	})
   680  	if err != nil {
   681  		return err
   682  	}
   683  	if len(tsAll) == 0 {
   684  		return nil
   685  	}
   686  
   687  	chg := m.state.NewChange("seed", "Initialize system state")
   688  	for _, ts := range tsAll {
   689  		chg.AddAll(ts)
   690  	}
   691  	m.state.EnsureBefore(0)
   692  
   693  	state.TagTimingsWithChange(perfTimings, chg)
   694  	perfTimings.Save(m.state)
   695  	return nil
   696  }
   697  
   698  // ResetBootOk is only useful for integration testing
   699  func (m *DeviceManager) ResetBootOk() {
   700  	m.bootOkRan = false
   701  	m.bootRevisionsUpdated = false
   702  }
   703  
   704  func (m *DeviceManager) ensureBootOk() error {
   705  	m.state.Lock()
   706  	defer m.state.Unlock()
   707  
   708  	if release.OnClassic {
   709  		return nil
   710  	}
   711  
   712  	// boot-ok/update-boot-revision is only relevant in run-mode
   713  	if m.SystemMode() != "run" {
   714  		return nil
   715  	}
   716  
   717  	if !m.bootOkRan {
   718  		deviceCtx, err := DeviceCtx(m.state, nil, nil)
   719  		if err != nil && err != state.ErrNoState {
   720  			return err
   721  		}
   722  		if err == nil {
   723  			if err := boot.MarkBootSuccessful(deviceCtx); err != nil {
   724  				return err
   725  			}
   726  		}
   727  		m.bootOkRan = true
   728  	}
   729  
   730  	if !m.bootRevisionsUpdated {
   731  		if err := snapstate.UpdateBootRevisions(m.state); err != nil {
   732  			return err
   733  		}
   734  		m.bootRevisionsUpdated = true
   735  	}
   736  
   737  	return nil
   738  }
   739  
   740  func (m *DeviceManager) ensureCloudInitRestricted() error {
   741  	m.state.Lock()
   742  	defer m.state.Unlock()
   743  
   744  	if m.cloudInitAlreadyRestricted {
   745  		return nil
   746  	}
   747  
   748  	var seeded bool
   749  	err := m.state.Get("seeded", &seeded)
   750  	if err != nil && err != state.ErrNoState {
   751  		return err
   752  	}
   753  
   754  	// On Ubuntu Core devices that have been seeded, we want to restrict
   755  	// cloud-init so that its more dangerous (for an IoT device at least)
   756  	// features are not exploitable after a device has been seeded. This allows
   757  	// device administrators and other tools (such as multipass) to still
   758  	// configure an Ubuntu Core device on first boot, and also allows cloud
   759  	// vendors to run cloud-init with only a specific data-source on subsequent
   760  	// boots but disallows arbitrary cloud-init {user,meta,vendor}-data to be
   761  	// attached to a device via a USB drive and inject code onto the device.
   762  
   763  	if seeded && !release.OnClassic {
   764  		opts := &sysconfig.CloudInitRestrictOptions{}
   765  
   766  		// check the current state of cloud-init, if it is disabled or already
   767  		// restricted then we have nothing to do
   768  		cloudInitStatus, err := cloudInitStatus()
   769  		if err != nil {
   770  			return err
   771  		}
   772  		statusMsg := ""
   773  
   774  		switch cloudInitStatus {
   775  		case sysconfig.CloudInitDisabledPermanently, sysconfig.CloudInitRestrictedBySnapd:
   776  			// already been permanently disabled, nothing to do
   777  			m.cloudInitAlreadyRestricted = true
   778  			return nil
   779  		case sysconfig.CloudInitNotFound:
   780  			// no cloud init at all
   781  			statusMsg = "not found"
   782  		case sysconfig.CloudInitUntriggered:
   783  			// hasn't been used
   784  			statusMsg = "reported to be in disabled state"
   785  		case sysconfig.CloudInitDone:
   786  			// is done being used
   787  			statusMsg = "reported to be done"
   788  		case sysconfig.CloudInitErrored:
   789  			// cloud-init errored, so we give the device admin / developer a few
   790  			// minutes to reboot the machine to re-run cloud-init and try again,
   791  			// otherwise we will disable cloud-init permanently
   792  
   793  			// initialize the time we first saw cloud-init in error state
   794  			if m.cloudInitErrorAttemptStart == nil {
   795  				// save the time we started the attempt to restrict
   796  				now := timeNow()
   797  				m.cloudInitErrorAttemptStart = &now
   798  				logger.Noticef("System initialized, cloud-init reported to be in error state, will disable in 3 minutes")
   799  			}
   800  
   801  			// check if 3 minutes have elapsed since we first saw cloud-init in
   802  			// error state
   803  			timeSinceFirstAttempt := timeNow().Sub(*m.cloudInitErrorAttemptStart)
   804  			if timeSinceFirstAttempt <= 3*time.Minute {
   805  				// we need to keep waiting for cloud-init, up to 3 minutes
   806  				nextCheck := 3*time.Minute - timeSinceFirstAttempt
   807  				m.state.EnsureBefore(nextCheck)
   808  				return nil
   809  			}
   810  			// otherwise, we timed out waiting for cloud-init to be fixed or
   811  			// rebooted and should restrict cloud-init
   812  			// we will restrict cloud-init below, but we need to force the
   813  			// disable, as by default RestrictCloudInit will error on state
   814  			// CloudInitErrored
   815  			opts.ForceDisable = true
   816  			statusMsg = "reported to be in error state after 3 minutes"
   817  		default:
   818  			// in unknown states we are conservative and let the device run for
   819  			// a while to see if it transitions to a known state, but eventually
   820  			// will disable anyways
   821  			fallthrough
   822  		case sysconfig.CloudInitEnabled:
   823  			// we will give cloud-init up to 5 minutes to try and run, if it
   824  			// still has not transitioned to some other known state, then we
   825  			// will give up waiting for it and disable it anyways
   826  
   827  			// initialize the first time we saw cloud-init in enabled state
   828  			if m.cloudInitEnabledInactiveAttemptStart == nil {
   829  				// save the time we started the attempt to restrict
   830  				now := timeNow()
   831  				m.cloudInitEnabledInactiveAttemptStart = &now
   832  			}
   833  
   834  			// keep re-scheduling again in 10 seconds until we hit 5 minutes
   835  			timeSinceFirstAttempt := timeNow().Sub(*m.cloudInitEnabledInactiveAttemptStart)
   836  			if timeSinceFirstAttempt <= 5*time.Minute {
   837  				// TODO: should we log a message here about waiting for cloud-init
   838  				//       to be in a "known state"?
   839  				m.state.EnsureBefore(10 * time.Second)
   840  				return nil
   841  			}
   842  
   843  			// otherwise, we gave cloud-init 5 minutes to run, if it's still not
   844  			// done disable it anyways
   845  			// note we we need to force the disable, as by default
   846  			// RestrictCloudInit will error on state CloudInitEnabled
   847  			opts.ForceDisable = true
   848  			statusMsg = "failed to transition to done or error state after 5 minutes"
   849  		}
   850  
   851  		// we should always have a model if we are seeded and are not on classic
   852  		model, err := m.Model()
   853  		if err != nil {
   854  			return err
   855  		}
   856  
   857  		// For UC20, we want to always disable cloud-init after it has run on
   858  		// first boot unless we are in a "real cloud", i.e. not using NoCloud,
   859  		// or if we installed cloud-init configuration from the gadget
   860  		if model.Grade() != asserts.ModelGradeUnset {
   861  			// always disable NoCloud/local datasources after first boot on
   862  			// uc20, this is because even if the gadget has a cloud.conf
   863  			// configuring NoCloud, the config installed by cloud-init should
   864  			// not work differently for later boots, so it's sufficient that
   865  			// NoCloud runs on first-boot and never again
   866  			opts.DisableAfterLocalDatasourcesRun = true
   867  		}
   868  
   869  		// now restrict/disable cloud-init
   870  		res, err := restrictCloudInit(cloudInitStatus, opts)
   871  		if err != nil {
   872  			return err
   873  		}
   874  
   875  		// log a message about what we did
   876  		actionMsg := ""
   877  		switch res.Action {
   878  		case "disable":
   879  			actionMsg = "disabled permanently"
   880  		case "restrict":
   881  			// log different messages depending on what datasource was used
   882  			if res.DataSource == "NoCloud" {
   883  				actionMsg = "set datasource_list to [ NoCloud ] and disabled auto-import by filesystem label"
   884  			} else {
   885  				// all other datasources just log that we limited it to that datasource
   886  				actionMsg = fmt.Sprintf("set datasource_list to [ %s ]", res.DataSource)
   887  			}
   888  		default:
   889  			return fmt.Errorf("internal error: unexpected action %s taken while restricting cloud-init", res.Action)
   890  		}
   891  		logger.Noticef("System initialized, cloud-init %s, %s", statusMsg, actionMsg)
   892  
   893  		m.cloudInitAlreadyRestricted = true
   894  	}
   895  
   896  	return nil
   897  }
   898  
   899  func (m *DeviceManager) ensureInstalled() error {
   900  	m.state.Lock()
   901  	defer m.state.Unlock()
   902  
   903  	if release.OnClassic {
   904  		return nil
   905  	}
   906  
   907  	if m.ensureInstalledRan {
   908  		return nil
   909  	}
   910  
   911  	if m.SystemMode() != "install" {
   912  		return nil
   913  	}
   914  
   915  	var seeded bool
   916  	err := m.state.Get("seeded", &seeded)
   917  	if err != nil && err != state.ErrNoState {
   918  		return err
   919  	}
   920  	if !seeded {
   921  		return nil
   922  	}
   923  
   924  	if m.changeInFlight("install-system") {
   925  		return nil
   926  	}
   927  
   928  	m.ensureInstalledRan = true
   929  
   930  	tasks := []*state.Task{}
   931  	setupRunSystem := m.state.NewTask("setup-run-system", i18n.G("Setup system for run mode"))
   932  	tasks = append(tasks, setupRunSystem)
   933  
   934  	chg := m.state.NewChange("install-system", i18n.G("Install the system"))
   935  	chg.AddAll(state.NewTaskSet(tasks...))
   936  
   937  	return nil
   938  }
   939  
   940  var timeNow = time.Now
   941  
   942  // StartOfOperationTime returns the time when snapd started operating,
   943  // and sets it in the state when called for the first time.
   944  // The StartOfOperationTime time is seed-time if available,
   945  // or current time otherwise.
   946  func (m *DeviceManager) StartOfOperationTime() (time.Time, error) {
   947  	var opTime time.Time
   948  	if m.preseed {
   949  		return opTime, fmt.Errorf("internal error: unexpected call to StartOfOperationTime in preseed mode")
   950  	}
   951  	err := m.state.Get("start-of-operation-time", &opTime)
   952  	if err == nil {
   953  		return opTime, nil
   954  	}
   955  	if err != nil && err != state.ErrNoState {
   956  		return opTime, err
   957  	}
   958  
   959  	// start-of-operation-time not set yet, use seed-time if available
   960  	var seedTime time.Time
   961  	err = m.state.Get("seed-time", &seedTime)
   962  	if err != nil && err != state.ErrNoState {
   963  		return opTime, err
   964  	}
   965  	if err == nil {
   966  		opTime = seedTime
   967  	} else {
   968  		opTime = timeNow()
   969  	}
   970  	m.state.Set("start-of-operation-time", opTime)
   971  	return opTime, nil
   972  }
   973  
   974  func markSeededInConfig(st *state.State) error {
   975  	var seedDone bool
   976  	tr := config.NewTransaction(st)
   977  	if err := tr.Get("core", "seed.loaded", &seedDone); err != nil && !config.IsNoOption(err) {
   978  		return err
   979  	}
   980  	if !seedDone {
   981  		if err := tr.Set("core", "seed.loaded", true); err != nil {
   982  			return err
   983  		}
   984  		tr.Commit()
   985  	}
   986  	return nil
   987  }
   988  
   989  func (m *DeviceManager) ensureSeedInConfig() error {
   990  	m.state.Lock()
   991  	defer m.state.Unlock()
   992  
   993  	if !m.ensureSeedInConfigRan {
   994  		// get global seeded option
   995  		var seeded bool
   996  		if err := m.state.Get("seeded", &seeded); err != nil && err != state.ErrNoState {
   997  			return err
   998  		}
   999  		if !seeded {
  1000  			// wait for ensure again, this is fine because
  1001  			// doMarkSeeded will run "EnsureBefore(0)"
  1002  			return nil
  1003  		}
  1004  
  1005  		// Sync seeding with the configuration state. We need to
  1006  		// do this here to ensure that old systems which did not
  1007  		// set the configuration on seeding get the configuration
  1008  		// update too.
  1009  		if err := markSeededInConfig(m.state); err != nil {
  1010  			return err
  1011  		}
  1012  		m.ensureSeedInConfigRan = true
  1013  	}
  1014  
  1015  	return nil
  1016  
  1017  }
  1018  
  1019  type ensureError struct {
  1020  	errs []error
  1021  }
  1022  
  1023  func (e *ensureError) Error() string {
  1024  	if len(e.errs) == 1 {
  1025  		return fmt.Sprintf("devicemgr: %v", e.errs[0])
  1026  	}
  1027  	parts := []string{"devicemgr:"}
  1028  	for _, e := range e.errs {
  1029  		parts = append(parts, e.Error())
  1030  	}
  1031  	return strings.Join(parts, "\n - ")
  1032  }
  1033  
  1034  // no \n allowed in warnings
  1035  var seedFailureFmt = `seeding failed with: %v. This indicates an error in your distribution, please see https://forum.snapcraft.io/t/16341 for more information.`
  1036  
  1037  // Ensure implements StateManager.Ensure.
  1038  func (m *DeviceManager) Ensure() error {
  1039  	var errs []error
  1040  
  1041  	if err := m.ensureSeeded(); err != nil {
  1042  		m.state.Lock()
  1043  		m.state.Warnf(seedFailureFmt, err)
  1044  		m.state.Unlock()
  1045  		errs = append(errs, fmt.Errorf("cannot seed: %v", err))
  1046  	}
  1047  
  1048  	if !m.preseed {
  1049  		if err := m.ensureCloudInitRestricted(); err != nil {
  1050  			errs = append(errs, err)
  1051  		}
  1052  
  1053  		if err := m.ensureOperational(); err != nil {
  1054  			errs = append(errs, err)
  1055  		}
  1056  
  1057  		if err := m.ensureBootOk(); err != nil {
  1058  			errs = append(errs, err)
  1059  		}
  1060  
  1061  		if err := m.ensureSeedInConfig(); err != nil {
  1062  			errs = append(errs, err)
  1063  		}
  1064  
  1065  		if err := m.ensureInstalled(); err != nil {
  1066  			errs = append(errs, err)
  1067  		}
  1068  	}
  1069  
  1070  	if len(errs) > 0 {
  1071  		return &ensureError{errs}
  1072  	}
  1073  
  1074  	return nil
  1075  }
  1076  
  1077  var errNoSaveSupport = errors.New("no save directory before UC20")
  1078  
  1079  // withSaveDir invokes a function making sure save dir is available.
  1080  // Under UC16/18 it returns errNoSaveSupport
  1081  // For UC20 it also checks that ubuntu-save is available/mounted.
  1082  func (m *DeviceManager) withSaveDir(f func() error) error {
  1083  	// we use the model to check whether this is a UC20 device
  1084  	model, err := m.Model()
  1085  	if err == state.ErrNoState {
  1086  		return fmt.Errorf("internal error: cannot access save dir before a model is set")
  1087  	}
  1088  	if err != nil {
  1089  		return err
  1090  	}
  1091  	if model.Grade() == asserts.ModelGradeUnset {
  1092  		return errNoSaveSupport
  1093  	}
  1094  	// at this point we need save available
  1095  	if !m.saveAvailable {
  1096  		return fmt.Errorf("internal error: save dir is unavailable")
  1097  	}
  1098  
  1099  	return f()
  1100  }
  1101  
  1102  // withSaveAssertDB invokes a function making the save device assertion
  1103  // backup database available to it.
  1104  // Under UC16/18 it returns errNoSaveSupport
  1105  // For UC20 it also checks that ubuntu-save is available/mounted.
  1106  func (m *DeviceManager) withSaveAssertDB(f func(*asserts.Database) error) error {
  1107  	return m.withSaveDir(func() error {
  1108  		// open an ancillary backup assertion database in save/device
  1109  		assertDB, err := sysdb.OpenAt(dirs.SnapDeviceSaveDir)
  1110  		if err != nil {
  1111  			return err
  1112  		}
  1113  		return f(assertDB)
  1114  	})
  1115  }
  1116  
  1117  // withKeypairMgr invokes a function making the device KeypairManager
  1118  // available to it.
  1119  // It uses the right location for the manager depending on UC16/18 vs 20,
  1120  // the latter uses ubuntu-save.
  1121  // For UC20 it also checks that ubuntu-save is available/mounted.
  1122  func (m *DeviceManager) withKeypairMgr(f func(asserts.KeypairManager) error) error {
  1123  	// we use the model to check whether this is a UC20 device
  1124  	// TODO: during a theoretical UC18->20 remodel the location of
  1125  	// keypair manager keys would move, we will need dedicated code
  1126  	// to deal with that, this code typically will return the old location
  1127  	// until a restart
  1128  	model, err := m.Model()
  1129  	if err == state.ErrNoState {
  1130  		return fmt.Errorf("internal error: cannot access device keypair manager before a model is set")
  1131  	}
  1132  	if err != nil {
  1133  		return err
  1134  	}
  1135  	underSave := false
  1136  	if model.Grade() != asserts.ModelGradeUnset {
  1137  		// on UC20 the keys are kept under the save dir
  1138  		underSave = true
  1139  	}
  1140  	where := dirs.SnapDeviceDir
  1141  	if underSave {
  1142  		// at this point we need save available
  1143  		if !m.saveAvailable {
  1144  			return fmt.Errorf("internal error: cannot access device keypair manager if ubuntu-save is unavailable")
  1145  		}
  1146  		where = dirs.SnapDeviceSaveDir
  1147  	}
  1148  	keypairMgr := m.cachedKeypairMgr
  1149  	if keypairMgr == nil {
  1150  		var err error
  1151  		keypairMgr, err = asserts.OpenFSKeypairManager(where)
  1152  		if err != nil {
  1153  			return err
  1154  		}
  1155  		m.cachedKeypairMgr = keypairMgr
  1156  	}
  1157  	return f(keypairMgr)
  1158  }
  1159  
  1160  // TODO:UC20: we need proper encapsulated support to read
  1161  // tpm-policy-auth-key from save if the latter can get unmounted on
  1162  // demand
  1163  
  1164  func (m *DeviceManager) keyPair() (asserts.PrivateKey, error) {
  1165  	device, err := m.device()
  1166  	if err != nil {
  1167  		return nil, err
  1168  	}
  1169  
  1170  	if device.KeyID == "" {
  1171  		return nil, state.ErrNoState
  1172  	}
  1173  
  1174  	var privKey asserts.PrivateKey
  1175  	err = m.withKeypairMgr(func(keypairMgr asserts.KeypairManager) (err error) {
  1176  		privKey, err = keypairMgr.Get(device.KeyID)
  1177  		if err != nil {
  1178  			return fmt.Errorf("cannot read device key pair: %v", err)
  1179  		}
  1180  		return nil
  1181  	})
  1182  	if err != nil {
  1183  		return nil, err
  1184  	}
  1185  	return privKey, nil
  1186  }
  1187  
  1188  // Registered returns a channel that is closed when the device is known to have been registered.
  1189  func (m *DeviceManager) Registered() <-chan struct{} {
  1190  	return m.reg
  1191  }
  1192  
  1193  // device returns current device state.
  1194  func (m *DeviceManager) device() (*auth.DeviceState, error) {
  1195  	return internal.Device(m.state)
  1196  }
  1197  
  1198  // setDevice sets the device details in the state.
  1199  func (m *DeviceManager) setDevice(device *auth.DeviceState) error {
  1200  	return internal.SetDevice(m.state, device)
  1201  }
  1202  
  1203  // Model returns the device model assertion.
  1204  func (m *DeviceManager) Model() (*asserts.Model, error) {
  1205  	return findModel(m.state)
  1206  }
  1207  
  1208  // Serial returns the device serial assertion.
  1209  func (m *DeviceManager) Serial() (*asserts.Serial, error) {
  1210  	return findSerial(m.state, nil)
  1211  }
  1212  
  1213  type SystemAction struct {
  1214  	Title string
  1215  	Mode  string
  1216  }
  1217  
  1218  type System struct {
  1219  	// Current is true when the system running now was installed from that
  1220  	// seed
  1221  	Current bool
  1222  	// Label of the seed system
  1223  	Label string
  1224  	// Model assertion of the system
  1225  	Model *asserts.Model
  1226  	// Brand information
  1227  	Brand *asserts.Account
  1228  	// Actions available for this system
  1229  	Actions []SystemAction
  1230  }
  1231  
  1232  var defaultSystemActions = []SystemAction{
  1233  	{Title: "Install", Mode: "install"},
  1234  }
  1235  var currentSystemActions = []SystemAction{
  1236  	{Title: "Reinstall", Mode: "install"},
  1237  	{Title: "Recover", Mode: "recover"},
  1238  	{Title: "Run normally", Mode: "run"},
  1239  }
  1240  var recoverSystemActions = []SystemAction{
  1241  	{Title: "Reinstall", Mode: "install"},
  1242  	{Title: "Run normally", Mode: "run"},
  1243  }
  1244  
  1245  var ErrNoSystems = errors.New("no systems seeds")
  1246  
  1247  // Systems list the available recovery/seeding systems. Returns the list of
  1248  // systems, ErrNoSystems when no systems seeds were found or other error.
  1249  func (m *DeviceManager) Systems() ([]*System, error) {
  1250  	// it's tough luck when we cannot determine the current system seed
  1251  	systemMode := m.SystemMode()
  1252  	currentSys, _ := currentSystemForMode(m.state, systemMode)
  1253  
  1254  	systemLabels, err := filepath.Glob(filepath.Join(dirs.SnapSeedDir, "systems", "*"))
  1255  	if err != nil && !os.IsNotExist(err) {
  1256  		return nil, fmt.Errorf("cannot list available systems: %v", err)
  1257  	}
  1258  	if len(systemLabels) == 0 {
  1259  		// maybe not a UC20 system
  1260  		return nil, ErrNoSystems
  1261  	}
  1262  
  1263  	var systems []*System
  1264  	for _, fpLabel := range systemLabels {
  1265  		label := filepath.Base(fpLabel)
  1266  		system, err := systemFromSeed(label, currentSys)
  1267  		if err != nil {
  1268  			// TODO:UC20 add a Broken field to the seed system like
  1269  			// we do for snap.Info
  1270  			logger.Noticef("cannot load system %q seed: %v", label, err)
  1271  			continue
  1272  		}
  1273  		systems = append(systems, system)
  1274  	}
  1275  	return systems, nil
  1276  }
  1277  
  1278  var ErrUnsupportedAction = errors.New("unsupported action")
  1279  
  1280  // Reboot triggers a reboot into the given systemLabel and mode.
  1281  //
  1282  // When called without a systemLabel and without a mode it will just
  1283  // trigger a regular reboot.
  1284  //
  1285  // When called without a systemLabel but with a mode it will use
  1286  // the current system to enter the given mode.
  1287  //
  1288  // Note that "recover" and "run" modes are only available for the
  1289  // current system.
  1290  func (m *DeviceManager) Reboot(systemLabel, mode string) error {
  1291  	rebootCurrent := func() {
  1292  		logger.Noticef("rebooting system")
  1293  		m.state.RequestRestart(state.RestartSystemNow)
  1294  	}
  1295  
  1296  	// most simple case: just reboot
  1297  	if systemLabel == "" && mode == "" {
  1298  		m.state.Lock()
  1299  		defer m.state.Unlock()
  1300  
  1301  		rebootCurrent()
  1302  		return nil
  1303  	}
  1304  
  1305  	// no systemLabel means "current" so get the current system label
  1306  	if systemLabel == "" {
  1307  		systemMode := m.SystemMode()
  1308  		currentSys, err := currentSystemForMode(m.state, systemMode)
  1309  		if err != nil {
  1310  			return fmt.Errorf("cannot get current system: %v", err)
  1311  		}
  1312  		systemLabel = currentSys.System
  1313  	}
  1314  
  1315  	switched := func(systemLabel string, sysAction *SystemAction) {
  1316  		logger.Noticef("rebooting into system %q in %q mode", systemLabel, sysAction.Mode)
  1317  		m.state.RequestRestart(state.RestartSystemNow)
  1318  	}
  1319  	// even if we are already in the right mode we restart here by
  1320  	// passing rebootCurrent as this is what the user requested
  1321  	return m.switchToSystemAndMode(systemLabel, mode, rebootCurrent, switched)
  1322  }
  1323  
  1324  // RequestSystemAction requests the provided system to be run in a
  1325  // given mode as specified by action.
  1326  // A system reboot will be requested when the request can be
  1327  // successfully carried out.
  1328  func (m *DeviceManager) RequestSystemAction(systemLabel string, action SystemAction) error {
  1329  	if systemLabel == "" {
  1330  		return fmt.Errorf("internal error: system label is unset")
  1331  	}
  1332  
  1333  	nop := func() {}
  1334  	switched := func(systemLabel string, sysAction *SystemAction) {
  1335  		logger.Noticef("restarting into system %q for action %q", systemLabel, sysAction.Title)
  1336  		m.state.RequestRestart(state.RestartSystemNow)
  1337  	}
  1338  	// we do nothing (nop) if the mode and system are the same
  1339  	return m.switchToSystemAndMode(systemLabel, action.Mode, nop, switched)
  1340  }
  1341  
  1342  // switchToSystemAndMode switches to given systemLabel and mode.
  1343  // If the systemLabel and mode are the same as current, it calls
  1344  // sameSystemAndMode. If successful otherwise it calls switched. Both
  1345  // are called with the state lock held.
  1346  func (m *DeviceManager) switchToSystemAndMode(systemLabel, mode string, sameSystemAndMode func(), switched func(systemLabel string, sysAction *SystemAction)) error {
  1347  	if err := checkSystemRequestConflict(m.state, systemLabel); err != nil {
  1348  		return err
  1349  	}
  1350  
  1351  	systemMode := m.SystemMode()
  1352  	// ignore the error to be robust in scenarios that
  1353  	// dont' stricly require currentSys to be carried through.
  1354  	// make sure that currentSys == nil does not break
  1355  	// the code below!
  1356  	// TODO: should we log the error?
  1357  	currentSys, _ := currentSystemForMode(m.state, systemMode)
  1358  
  1359  	systemSeedDir := filepath.Join(dirs.SnapSeedDir, "systems", systemLabel)
  1360  	if _, err := os.Stat(systemSeedDir); err != nil {
  1361  		// XXX: should we wrap this instead return a naked stat error?
  1362  		return err
  1363  	}
  1364  	system, err := systemFromSeed(systemLabel, currentSys)
  1365  	if err != nil {
  1366  		return fmt.Errorf("cannot load seed system: %v", err)
  1367  	}
  1368  
  1369  	var sysAction *SystemAction
  1370  	for _, act := range system.Actions {
  1371  		if mode == act.Mode {
  1372  			sysAction = &act
  1373  			break
  1374  		}
  1375  	}
  1376  	if sysAction == nil {
  1377  		// XXX: provide more context here like what mode was requested?
  1378  		return ErrUnsupportedAction
  1379  	}
  1380  
  1381  	// XXX: requested mode is valid; only current system has 'run' and
  1382  	// recover 'actions'
  1383  
  1384  	switch systemMode {
  1385  	case "recover", "run":
  1386  		// if going from recover to recover or from run to run and the systems
  1387  		// are the same do nothing
  1388  		if systemMode == sysAction.Mode && currentSys != nil && systemLabel == currentSys.System {
  1389  			m.state.Lock()
  1390  			defer m.state.Unlock()
  1391  			sameSystemAndMode()
  1392  			return nil
  1393  		}
  1394  	case "install":
  1395  		// requesting system actions in install mode does not make sense atm
  1396  		//
  1397  		// TODO:UC20: maybe factory hooks will be able to something like
  1398  		// this?
  1399  		return ErrUnsupportedAction
  1400  	default:
  1401  		// probably test device manager mocking problem, or also potentially
  1402  		// missing modeenv
  1403  		return fmt.Errorf("internal error: unexpected manager system mode %q", systemMode)
  1404  	}
  1405  
  1406  	m.state.Lock()
  1407  	defer m.state.Unlock()
  1408  
  1409  	deviceCtx, err := DeviceCtx(m.state, nil, nil)
  1410  	if err != nil {
  1411  		return err
  1412  	}
  1413  	if err := boot.SetRecoveryBootSystemAndMode(deviceCtx, systemLabel, mode); err != nil {
  1414  		return fmt.Errorf("cannot set device to boot into system %q in mode %q: %v", systemLabel, mode, err)
  1415  	}
  1416  
  1417  	switched(systemLabel, sysAction)
  1418  	return nil
  1419  }
  1420  
  1421  // implement storecontext.Backend
  1422  
  1423  type storeContextBackend struct {
  1424  	*DeviceManager
  1425  }
  1426  
  1427  func (scb storeContextBackend) Device() (*auth.DeviceState, error) {
  1428  	return scb.DeviceManager.device()
  1429  }
  1430  
  1431  func (scb storeContextBackend) SetDevice(device *auth.DeviceState) error {
  1432  	return scb.DeviceManager.setDevice(device)
  1433  }
  1434  
  1435  func (scb storeContextBackend) ProxyStore() (*asserts.Store, error) {
  1436  	st := scb.DeviceManager.state
  1437  	return proxyStore(st, config.NewTransaction(st))
  1438  }
  1439  
  1440  // SignDeviceSessionRequest produces a signed device-session-request with for given serial assertion and nonce.
  1441  func (scb storeContextBackend) SignDeviceSessionRequest(serial *asserts.Serial, nonce string) (*asserts.DeviceSessionRequest, error) {
  1442  	if serial == nil {
  1443  		// shouldn't happen, but be safe
  1444  		return nil, fmt.Errorf("internal error: cannot sign a session request without a serial")
  1445  	}
  1446  
  1447  	privKey, err := scb.DeviceManager.keyPair()
  1448  	if err == state.ErrNoState {
  1449  		return nil, fmt.Errorf("internal error: inconsistent state with serial but no device key")
  1450  	}
  1451  	if err != nil {
  1452  		return nil, err
  1453  	}
  1454  
  1455  	a, err := asserts.SignWithoutAuthority(asserts.DeviceSessionRequestType, map[string]interface{}{
  1456  		"brand-id":  serial.BrandID(),
  1457  		"model":     serial.Model(),
  1458  		"serial":    serial.Serial(),
  1459  		"nonce":     nonce,
  1460  		"timestamp": time.Now().UTC().Format(time.RFC3339),
  1461  	}, nil, privKey)
  1462  	if err != nil {
  1463  		return nil, err
  1464  	}
  1465  
  1466  	return a.(*asserts.DeviceSessionRequest), nil
  1467  }
  1468  
  1469  func (m *DeviceManager) StoreContextBackend() storecontext.Backend {
  1470  	return storeContextBackend{m}
  1471  }
  1472  
  1473  func (m *DeviceManager) hasFDESetupHook() (bool, error) {
  1474  	// state must be locked
  1475  	st := m.state
  1476  
  1477  	deviceCtx, err := DeviceCtx(st, nil, nil)
  1478  	if err != nil {
  1479  		return false, fmt.Errorf("cannot get device context: %v", err)
  1480  	}
  1481  
  1482  	kernelInfo, err := snapstate.KernelInfo(st, deviceCtx)
  1483  	if err != nil {
  1484  		return false, fmt.Errorf("cannot get kernel info: %v", err)
  1485  	}
  1486  	return hasFDESetupHookInKernel(kernelInfo), nil
  1487  }
  1488  
  1489  func (m *DeviceManager) runFDESetupHook(op string, params *boot.FDESetupHookParams) ([]byte, error) {
  1490  	// TODO:UC20: when this runs on refresh we need to be very careful
  1491  	// that we never run this when the kernel is not fully configured
  1492  	// i.e. when there are no security profiles for the hook
  1493  
  1494  	// state must be locked
  1495  	st := m.state
  1496  
  1497  	deviceCtx, err := DeviceCtx(st, nil, nil)
  1498  	if err != nil {
  1499  		return nil, fmt.Errorf("cannot get device context to run fde-setup hook: %v", err)
  1500  	}
  1501  	kernelInfo, err := snapstate.KernelInfo(st, deviceCtx)
  1502  	if err != nil {
  1503  		return nil, fmt.Errorf("cannot get kernel info to run fde-setup hook: %v", err)
  1504  	}
  1505  	hooksup := &hookstate.HookSetup{
  1506  		Snap:     kernelInfo.InstanceName(),
  1507  		Revision: kernelInfo.Revision,
  1508  		Hook:     "fde-setup",
  1509  		// XXX: should this be configurable somehow?
  1510  		Timeout: 5 * time.Minute,
  1511  	}
  1512  	req := &fde.SetupRequest{
  1513  		Op:      op,
  1514  		Key:     &params.Key,
  1515  		KeyName: params.KeyName,
  1516  		// TODO: include boot chains
  1517  	}
  1518  	for _, model := range params.Models {
  1519  		req.Models = append(req.Models, map[string]string{
  1520  			"series":     model.Series(),
  1521  			"brand-id":   model.BrandID(),
  1522  			"model":      model.Model(),
  1523  			"grade":      string(model.Grade()),
  1524  			"signkey-id": model.SignKeyID(),
  1525  		})
  1526  	}
  1527  	contextData := map[string]interface{}{
  1528  		"fde-setup-request": req,
  1529  	}
  1530  	st.Unlock()
  1531  	defer st.Lock()
  1532  	context, err := m.hookMgr.EphemeralRunHook(context.Background(), hooksup, contextData)
  1533  	if err != nil {
  1534  		return nil, fmt.Errorf("cannot run hook for %q: %v", op, err)
  1535  	}
  1536  	// the hook is expected to call "snapctl fde-setup-result" which
  1537  	// wil set the "fde-setup-result" value on the task
  1538  	var hookResult []byte
  1539  	context.Lock()
  1540  	err = context.Get("fde-setup-result", &hookResult)
  1541  	context.Unlock()
  1542  	if err != nil {
  1543  		return nil, fmt.Errorf("cannot get result from fde-setup hook %q: %v", op, err)
  1544  	}
  1545  
  1546  	return hookResult, nil
  1547  }
  1548  
  1549  func (m *DeviceManager) checkFDEFeatures(st *state.State) error {
  1550  	// Run fde-setup hook with "op":"features". If the hook
  1551  	// returns any {"features":[...]} reply we consider the
  1552  	// hardware supported. If the hook errors or if it returns
  1553  	// {"error":"hardware-unsupported"} we don't.
  1554  	output, err := m.runFDESetupHook("features", &boot.FDESetupHookParams{})
  1555  	if err != nil {
  1556  		return err
  1557  	}
  1558  	var res struct {
  1559  		Features []string `json:"features"`
  1560  		Error    string   `json:"error"`
  1561  	}
  1562  	if err := json.Unmarshal(output, &res); err != nil {
  1563  		return fmt.Errorf("cannot parse hook output %q: %v", output, err)
  1564  	}
  1565  	if res.Features == nil && res.Error == "" {
  1566  		return fmt.Errorf(`cannot use hook: neither "features" nor "error" returned`)
  1567  	}
  1568  	if res.Error != "" {
  1569  		return fmt.Errorf("cannot use hook: it returned error: %v", res.Error)
  1570  	}
  1571  	return nil
  1572  }
  1573  
  1574  func hasFDESetupHookInKernel(kernelInfo *snap.Info) bool {
  1575  	_, ok := kernelInfo.Hooks["fde-setup"]
  1576  	return ok
  1577  }
  1578  
  1579  type fdeSetupHandler struct {
  1580  	context *hookstate.Context
  1581  }
  1582  
  1583  func newFdeSetupHandler(ctx *hookstate.Context) hookstate.Handler {
  1584  	return fdeSetupHandler{context: ctx}
  1585  }
  1586  
  1587  func (h fdeSetupHandler) Before() error {
  1588  	return nil
  1589  }
  1590  
  1591  func (h fdeSetupHandler) Done() error {
  1592  	return nil
  1593  }
  1594  
  1595  func (h fdeSetupHandler) Error(err error) error {
  1596  	return nil
  1597  }