snapstate

package
v0.0.0-...-c7fba9c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2021 License: GPL-3.0 Imports: 56 Imported by: 0

Documentation

Overview

Package snapstate implements the manager and state aspects responsible for the installation and removal of snaps.

Index

Constants

View Source
const (
	IgnoreHookError = 1 << iota
	TrackHookError
	UseConfigDefaults
)

control flags for "Configure()"

View Source
const (
	DownloadAndChecksDoneEdge = state.TaskSetEdge("download-and-checks-done")
	BeginEdge                 = state.TaskSetEdge("begin")
	BeforeHooksEdge           = state.TaskSetEdge("before-hooks")
	HooksEdge                 = state.TaskSetEdge("hooks")
)

Variables

View Source
var (
	CanAutoRefresh        func(st *state.State) (bool, error)
	CanManageRefreshes    func(st *state.State) bool
	IsOnMeteredConnection func() (bool, error)
)

hooks setup by devicestate

View Source
var AutoAliases func(st *state.State, info *snap.Info) (map[string]string, error)

AutoAliases allows to hook support for retrieving the automatic aliases of a snap.

View Source
var AutoRefreshAssertions func(st *state.State, userID int) error

AutoRefreshAssertions allows to hook fetching of important assertions into the Autorefresh function.

View Source
var AutomaticSnapshot func(st *state.State, instanceName string) (ts *state.TaskSet, err error)

AutomaticSnapshot allows to hook snapshot manager's AutomaticSnapshot.

View Source
var AutomaticSnapshotExpiration func(st *state.State) (time.Duration, error)
View Source
var CheckHealthHook = func(st *state.State, snapName string, rev snap.Revision) *state.Task {
	panic("internal error: snapstate.CheckHealthHook is unset")
}
View Source
var Configure = func(st *state.State, snapName string, patch map[string]interface{}, flags int) *state.TaskSet {
	panic("internal error: snapstate.Configure is unset")
}
View Source
var (
	DeviceCtx func(st *state.State, task *state.Task, providedDeviceCtx DeviceContext) (DeviceContext, error)
)

Hook setup by devicestate to pick a device context from state, optional task or an optionally pre-provided one. It's expected to return ErrNoState if a model assertion is not yet known.

View Source
var EnforcedValidationSets func(st *state.State) (*snapasserts.ValidationSets, error)

EnforcedValidationSets allows to hook getting of validation sets in enforce mode into installation/refresh/removal of snaps. It gets hooked from assertstate.

View Source
var EnsureSnapAbsentFromQuotaGroup = func(st *state.State, snap string) error {
	panic("internal error: snapstate.EnsureSnapAbsentFromQuotaGroup is unset")
}
View Source
var ErrMissingExpectedResult = fmt.Errorf("unexpectedly empty response from the server (try again later)")
View Source
var ErrNoCurrent = errors.New("snap has no current revision")
View Source
var ErrNothingToDo = errors.New("nothing to do")
View Source
var EstimateSnapshotSize func(st *state.State, instanceName string, users []string) (uint64, error)
View Source
var FinalTasks = []string{"mark-seeded", "set-model"}

FinalTasks are task kinds for final tasks in a change which means no further change work should be performed afterward, usually these are tasks that commit a full system transition.

View Source
var PolicyFor func(snap.Type, *asserts.Model) Policy = policyForUnset
View Source
var (
	Remodeling func(st *state.State) bool
)

Hook setup by devicestate to know whether a remodeling is in progress.

View Source
var SecurityProfilesRemoveLate = func(snapName string, rev snap.Revision, typ snap.Type) error {
	panic("internal error: snapstate.SecurityProfilesRemoveLate is unset")
}
View Source
var SetupGateAutoRefreshHook = func(st *state.State, snapName string, base, restart bool, affectingSnaps map[string]bool) *state.Task {
	panic("internal error: snapstate.SetupAutoRefreshGatingHook is unset")
}
View Source
var SetupInstallHook = func(st *state.State, snapName string) *state.Task {
	panic("internal error: snapstate.SetupInstallHook is unset")
}
View Source
var SetupPostRefreshHook = func(st *state.State, snapName string) *state.Task {
	panic("internal error: snapstate.SetupPostRefreshHook is unset")
}
View Source
var SetupPreRefreshHook = func(st *state.State, snapName string) *state.Task {
	panic("internal error: snapstate.SetupPreRefreshHook is unset")
}
View Source
var SetupRemoveHook = func(st *state.State, snapName string) *state.Task {
	panic("internal error: snapstate.SetupRemoveHook is unset")
}
View Source
var SnapServiceOptions = func(st *state.State, instanceName string, grps map[string]*quota.Group) (opts *wrappers.SnapServiceOptions, err error) {
	panic("internal error: snapstate.SnapServiceOptions is unset")
}

SnapServiceOptions is a hook set by servicestate.

View Source
var ValidateRefreshes func(st *state.State, refreshes []*snap.Info, ignoreValidation map[string]bool, userID int, deviceCtx DeviceContext) (validated []*snap.Info, err error)

ValidateRefreshes allows to hook validation into the handling of refresh candidates.

Functions

func ActiveInfos

func ActiveInfos(st *state.State) ([]*snap.Info, error)

ActiveInfos returns information about all active snaps.

func AddAffectedSnapsByAttr

func AddAffectedSnapsByAttr(attr string, f AffectedSnapsFunc)

AddAffectedSnapsByAttrs registers an AffectedSnapsFunc for returning the affected snaps for tasks sporting the given identifying attribute, to use in conflicts detection.

func AddAffectedSnapsByKind

func AddAffectedSnapsByKind(kind string, f AffectedSnapsFunc)

AddAffectedSnapsByKind registers an AffectedSnapsFunc for returning the affected snaps for tasks of the given kind, to use in conflicts detection. Whenever possible using AddAffectedSnapsByAttr should be preferred.

func AddCheckSnapCallback

func AddCheckSnapCallback(check CheckSnapCallback)

AddCheckSnapCallback installs a callback to check a snap for installation or refresh.

func AddLinkSnapParticipant

func AddLinkSnapParticipant(p LinkSnapParticipant)

AddLinkSnapParticipant adds a participant in the link/unlink operations.

func AffectedByRefreshCandidates

func AffectedByRefreshCandidates(st *state.State) (map[string]*AffectedSnapInfo, error)

AffectedByRefreshCandidates returns information about all snaps affected by current refresh-candidates in the state.

func Alias

func Alias(st *state.State, instanceName, app, alias string) (*state.TaskSet, error)

Alias sets up a manual alias from alias to app in snapName.

func All

func All(st *state.State) (map[string]*SnapState, error)

All retrieves return a map from name to SnapState for all current snaps in the system state.

func AutoRefresh

func AutoRefresh(ctx context.Context, st *state.State) ([]string, []*state.TaskSet, error)

AutoRefresh is the wrapper that will do a refresh of all the installed snaps on the system. In addition to that it will also refresh important assertions.

func AutoRefreshForGatingSnap

func AutoRefreshForGatingSnap(st *state.State, gatingSnap string) error

AutoRefreshForGatingSnap triggers an auto-refresh change for all snaps held by the given gating snap. This should only be called if the gate-auto-refresh-hook feature is enabled. TODO: this should be restricted as it doesn't take refresh timer/refresh hold into account.

func BootBaseInfo

func BootBaseInfo(st *state.State, deviceCtx DeviceContext) (*snap.Info, error)

BootBaseInfo finds the boot base snap's info for the given device context.

func CheckChangeConflict

func CheckChangeConflict(st *state.State, instanceName string, snapst *SnapState) error

CheckChangeConflict ensures that for the given instanceName no other changes that alters the snap (like remove, install, refresh) are in progress. It also ensures that snapst (if not nil) did not get modified. If a conflict is detected an error is returned.

func CheckChangeConflictMany

func CheckChangeConflictMany(st *state.State, instanceNames []string, ignoreChangeID string) error

CheckChangeConflictMany ensures that for the given instanceNames no other changes that alters the snaps (like remove, install, refresh) are in progress. If a conflict is detected an error is returned.

It's like CheckChangeConflict, but for multiple snaps, and does not check snapst.

func CheckChangeConflictRunExclusively

func CheckChangeConflictRunExclusively(st *state.State, newChangeKind string) error

CheckChangeConflictRunExclusively checks for conflicts with a new change which must be run when no other changes are running.

func ConfigDefaults

func ConfigDefaults(st *state.State, deviceCtx DeviceContext, snapName string) (map[string]interface{}, error)

ConfigDefaults returns the configuration defaults for the snap as specified in the gadget for the given device context. If gadget is absent or the snap has no snap-id it returns ErrNoState.

func ConfigureSnap

func ConfigureSnap(st *state.State, snapName string, confFlags int) *state.TaskSet

ConfigureSnap returns a set of tasks to configure snapName as done during installation/refresh.

func CurrentInfo

func CurrentInfo(st *state.State, name string) (*snap.Info, error)

CurrentInfo returns the information about the current revision of a snap with the given name.

func Disable

func Disable(st *state.State, name string) (*state.TaskSet, error)

Disable sets a snap to the inactive state

func DisableAllAliases

func DisableAllAliases(st *state.State, instanceName string) (*state.TaskSet, error)

DisableAllAliases disables all aliases of a snap, removing all manual ones.

func Enable

func Enable(st *state.State, name string) (*state.TaskSet, error)

Enable sets a snap to the active state

func FinishRestart

func FinishRestart(task *state.Task, snapsup *SnapSetup) (err error)

FinishRestart will return a Retry error if there is a pending restart and a real error if anything went wrong (like a rollback across restarts). For snapd snap updates this will also rerun wrappers generation to fully catch up with any change.

func GadgetConnections

func GadgetConnections(st *state.State, deviceCtx DeviceContext) ([]gadget.Connection, error)

GadgetConnections returns the interface connection instructions specified in the gadget for the given device context. If gadget is absent it returns ErrNoState.

func GadgetInfo

func GadgetInfo(st *state.State, deviceCtx DeviceContext) (*snap.Info, error)

GadgetInfo finds the gadget snap's info for the given device context.

func Get

func Get(st *state.State, name string, snapst *SnapState) error

Get retrieves the SnapState of the given snap.

func HardNothingRunningRefreshCheck

func HardNothingRunningRefreshCheck(info *snap.Info) error

HardNothingRunningRefreshCheck looks if there are any undesired processes alive.

The check is designed to run late in the refresh pipeline, after stopping snap services. At this point non-enduring services should be stopped, hooks should no longer run, and applications should be barred from running externally (e.g. by using a new inhibition mechanism for snap run).

The check fails if any process belonging to the snap, apart from services that are enduring refresh, is still alive. If a snap is busy it cannot be refreshed and the refresh process is aborted.

func HasSnapOfType

func HasSnapOfType(st *state.State, snapType snap.Type) (bool, error)

func HoldRefresh

func HoldRefresh(st *state.State, gatingSnap string, holdDuration time.Duration, affectingSnaps ...string) error

HoldRefresh marks affectingSnaps as held for refresh for up to holdTime. HoldTime of zero denotes maximum allowed hold time. Holding may fail for only some snaps in which case HoldError is returned and it contains the details of failed ones.

func Info

func Info(st *state.State, name string, revision snap.Revision) (*snap.Info, error)

Info returns the information about the snap with given name and revision. Works also for a mounted candidate snap in the process of being installed.

func InjectAutoConnect

func InjectAutoConnect(mainTask *state.Task, snapsup *SnapSetup)

func InjectTasks

func InjectTasks(mainTask *state.Task, extraTasks *state.TaskSet)

InjectTasks makes all the halt tasks of the mainTask wait for extraTasks; extraTasks join the same lane and change as the mainTask.

func Install

func Install(ctx context.Context, st *state.State, name string, opts *RevisionOptions, userID int, flags Flags) (*state.TaskSet, error)

Install returns a set of tasks for installing a snap. Note that the state must be locked by the caller.

The returned TaskSet will contain a DownloadAndChecksDoneEdge.

func InstallMany

func InstallMany(st *state.State, names []string, userID int) ([]string, []*state.TaskSet, error)

InstallMany installs everything from the given list of names. Note that the state must be locked by the caller.

func InstallPath

func InstallPath(st *state.State, si *snap.SideInfo, path, instanceName, channel string, flags Flags) (*state.TaskSet, *snap.Info, error)

InstallPath returns a set of tasks for installing a snap from a file path and the snap.Info for the given snap.

Note that the state must be locked by the caller. The provided SideInfo can contain just a name which results in a local revision and sideloading, or full metadata in which case it the snap will appear as installed from the store.

func InstallWithDeviceContext

func InstallWithDeviceContext(ctx context.Context, st *state.State, name string, opts *RevisionOptions, userID int, flags Flags, deviceCtx DeviceContext, fromChange string) (*state.TaskSet, error)

InstallWithDeviceContext returns a set of tasks for installing a snap. It will query for the snap with the given deviceCtx. Note that the state must be locked by the caller.

The returned TaskSet will contain a DownloadAndChecksDoneEdge.

func Installing

func Installing(st *state.State) bool

Installing returns whether there's an in-progress installation.

func KernelInfo

func KernelInfo(st *state.State, deviceCtx DeviceContext) (*snap.Info, error)

KernelInfo finds the kernel snap's info for the given device context.

func LinkNewBaseOrKernel

func LinkNewBaseOrKernel(st *state.State, name string) (*state.TaskSet, error)

LinkNewBaseOrKernel will create prepare/link-snap tasks for a remodel

func MockCheckSnapCallbacks

func MockCheckSnapCallbacks(checks []CheckSnapCallback) (restore func())

func MockLinkSnapParticipants

func MockLinkSnapParticipants(ps []LinkSnapParticipant) (restore func())

MockLinkSnapParticipants replaces the list of link snap participants for testing.

func MockOsutilCheckFreeSpace

func MockOsutilCheckFreeSpace(mock func(path string, minSize uint64) error) (restore func())

func MockRefreshCandidate

func MockRefreshCandidate(snapSetup *SnapSetup, version string) interface{}

for testing outside of snapstate

func ModelFromTask

func ModelFromTask(task *state.Task) (*asserts.Model, error)

ModelFromTask returns a model assertion through the device context for the task.

func NewTaskProgressAdapterLocked

func NewTaskProgressAdapterLocked(t *state.Task) progress.Meter

NewTaskProgressAdapterUnlocked creates an adapter of the task into a progress.Meter to use while the state is locked

func NewTaskProgressAdapterUnlocked

func NewTaskProgressAdapterUnlocked(t *state.Task) progress.Meter

NewTaskProgressAdapterUnlocked creates an adapter of the task into a progress.Meter to use while the state is unlocked

func NumSnaps

func NumSnaps(st *state.State) (int, error)

NumSnaps returns the number of installed snaps.

func Prefer

func Prefer(st *state.State, name string) (*state.TaskSet, error)

Prefer enables all aliases of a snap in preference to conflicting aliases of other snaps whose aliases will be disabled (removed for manual ones).

func ProceedWithRefresh

func ProceedWithRefresh(st *state.State, gatingSnap string) error

ProceedWithRefresh unblocks all snaps held by gatingSnap for refresh. This should be called for --proceed on the gatingSnap.

func RefreshCandidates

func RefreshCandidates(st *state.State, user *auth.UserState) ([]*snap.Info, error)

RefreshCandidates gets a list of candidates for update Note that the state must be locked by the caller.

func Remove

func Remove(st *state.State, name string, revision snap.Revision, flags *RemoveFlags) (*state.TaskSet, error)

Remove returns a set of tasks for removing snap. Note that the state must be locked by the caller.

func RemoveManualAlias

func RemoveManualAlias(st *state.State, alias string) (ts *state.TaskSet, instanceName string, err error)

RemoveManualAlias removes a manual alias.

func RemoveMany

func RemoveMany(st *state.State, names []string) ([]string, []*state.TaskSet, error)

RemoveMany removes everything from the given list of names. Note that the state must be locked by the caller.

func ReplaceStore

func ReplaceStore(state *state.State, store StoreService)

ReplaceStore replaces the store used by the manager.

func Revert

func Revert(st *state.State, name string, flags Flags) (*state.TaskSet, error)

Revert returns a set of tasks for reverting to the previous version of the snap. Note that the state must be locked by the caller.

func RevertToRevision

func RevertToRevision(st *state.State, name string, rev snap.Revision, flags Flags) (*state.TaskSet, error)

func Set

func Set(st *state.State, name string, snapst *SnapState)

Set sets the SnapState of the given snap, overwriting any earlier state. Note that a SnapState with an empty Sequence will be treated as if snapst was nil and name will be deleted from the state.

func SetTaskSnapSetup

func SetTaskSnapSetup(t *state.Task, snapsup *SnapSetup) error

SetTaskSnapSetup writes the given SnapSetup to the provided task's snap-setup-task Task, or to the task itself if the task does not have a snap-setup-task (i.e. it _is_ the snap-setup-task)

func SoftNothingRunningRefreshCheck

func SoftNothingRunningRefreshCheck(info *snap.Info) error

SoftNothingRunningRefreshCheck looks if there are at most only service processes alive.

The check is designed to run early in the refresh pipeline. Before downloading or stopping services for the update, we can check that only services are running, that is, that no non-service apps or hooks are currently running.

Since services are stopped during the update this provides a good early precondition check. The check is also deliberately racy as existing snap commands can fork new processes or existing processes can die. After the soft check passes the user is free to start snap applications and block the hard check.

func Switch

func Switch(st *state.State, name string, opts *RevisionOptions) (*state.TaskSet, error)

Switch switches a snap to a new channel and/or cohort

func TransitionCore

func TransitionCore(st *state.State, oldName, newName string) ([]*state.TaskSet, error)

TransitionCore transitions from an old core snap name to a new core snap name. It is used for the ubuntu-core -> core transition (that is not just a rename because the two snaps have different snapIDs)

Note that this function makes some assumptions like: - no aliases setup for both snaps - no data needs to be copied - all interfaces are absolutely identical on both new and old Do not use this as a general way to transition from snap A to snap B.

func TryPath

func TryPath(st *state.State, name, path string, flags Flags) (*state.TaskSet, error)

TryPath returns a set of tasks for trying a snap from a file path. Note that the state must be locked by the caller.

func Update

func Update(st *state.State, name string, opts *RevisionOptions, userID int, flags Flags) (*state.TaskSet, error)

Update initiates a change updating a snap. Note that the state must be locked by the caller.

The returned TaskSet will contain a DownloadAndChecksDoneEdge.

func UpdateBootRevisions

func UpdateBootRevisions(st *state.State) error

UpdateBootRevisions synchronizes the active kernel and OS snap versions with the versions that actually booted. This is needed because a system may install "os=v2" but that fails to boot. The bootloader fallback logic will revert to "os=v1" but on the filesystem snappy still has the "active" version set to "v2" which is misleading. This code will check what kernel/os booted and set those versions active.To do this it creates a Change and kicks start it directly.

func UpdateMany

func UpdateMany(ctx context.Context, st *state.State, names []string, userID int, flags *Flags) ([]string, []*state.TaskSet, error)

UpdateMany updates everything from the given list of names that the store says is updateable. If the list is empty, update everything. Note that the state must be locked by the caller.

func UpdateWithDeviceContext

func UpdateWithDeviceContext(st *state.State, name string, opts *RevisionOptions, userID int, flags Flags, deviceCtx DeviceContext, fromChange string) (*state.TaskSet, error)

UpdateWithDeviceContext initiates a change updating a snap. It will query for the snap with the given deviceCtx. Note that the state must be locked by the caller.

The returned TaskSet will contain a DownloadAndChecksDoneEdge.

Types

type AffectedSnapInfo

type AffectedSnapInfo struct {
	Restart        bool
	Base           bool
	AffectingSnaps map[string]bool
}

type AffectedSnapsFunc

type AffectedSnapsFunc func(*state.Task) ([]string, error)

An AffectedSnapsFunc returns a list of affected snap names for the given supported task.

type AliasConflictError

type AliasConflictError struct {
	Snap      string
	Alias     string
	Reason    string
	Conflicts map[string][]string
}

func (*AliasConflictError) Error

func (e *AliasConflictError) Error() string

type AliasTarget

type AliasTarget struct {
	Manual string `json:"manual,omitempty"`
	Auto   string `json:"auto,omitempty"`
}

AliasTarget carries the targets of an alias in the context of snap. If Manual is set it is the target of an enabled manual alias. Auto is set to the target for an automatic alias, enabled or disabled depending on the automatic aliases flag state.

func (*AliasTarget) Effective

func (at *AliasTarget) Effective(autoDisabled bool) string

Effective returns the target to use considering whether automatic aliases are disabled for the whole snap (autoDisabled), returns "" if the alias is disabled.

type BusySnapError

type BusySnapError struct {
	SnapInfo *snap.Info
	// contains filtered or unexported fields
}

BusySnapError indicates that snap has apps or hooks running and cannot refresh.

func (*BusySnapError) Error

func (err *BusySnapError) Error() string

Error formats an error string describing what is running.

func (*BusySnapError) PendingSnapRefreshInfo

func (err *BusySnapError) PendingSnapRefreshInfo() *userclient.PendingSnapRefreshInfo

PendingSnapRefreshInfo computes information necessary to perform user notification of postponed refresh of a snap, based on the information about snap "business".

The returned value contains the instance name of the snap as well as, if possible, information relevant for desktop notification services, such as application name and the snapd-generated desktop file name.

func (BusySnapError) Pids

func (err BusySnapError) Pids() []int

Pids returns the set of process identifiers that are running.

Since this list is a snapshot it should be only acted upon if there is an external synchronization system applied (e.g. all processes are frozen) at the time the snapshot was taken.

The list is intended for snapd to forcefully kill all processes for a forced refresh scenario.

type ChangeConflictError

type ChangeConflictError struct {
	Snap       string
	ChangeKind string
	// a Message is optional, otherwise one is composed from the other information
	Message string
}

ChangeConflictError represents an error because of snap conflicts between changes.

func (*ChangeConflictError) Error

func (e *ChangeConflictError) Error() string

type CheckSnapCallback

type CheckSnapCallback func(st *state.State, snap, curSnap *snap.Info, snapf snap.Container, flags Flags, deviceCtx DeviceContext) error

CheckSnapCallback defines callbacks for checking a snap for installation or refresh.

type DeviceContext

type DeviceContext interface {
	// GroundContext returns a context corresponding to the
	// original model of the device for a remodel, or a context
	// equivalent to this one otherwise, except in both cases
	// Store cannot be used and must panic.
	GroundContext() DeviceContext

	// Store returns the store service to use under this context or nil if the snapstate store is appropriate.
	Store() StoreService

	// ForRemodeling returns whether this context is for use over a remodeling.
	ForRemodeling() bool

	// SystemMode returns the system  mode (run,install,recover,...).
	SystemMode() string

	// DeviceContext should be usable as boot.Device
	boot.Device
}

A DeviceContext provides for operating as a given device and with its brand store either for normal operation or over a remodeling.

func DeviceCtxFromState

func DeviceCtxFromState(st *state.State, providedDeviceCtx DeviceContext) (DeviceContext, error)

DeviceCtxFromState returns a device context if a model assertion is available. Otherwise it returns a ChangeConflictError about being too early unless an pre-provided DeviceContext is passed in.

func DevicePastSeeding

func DevicePastSeeding(st *state.State, providedDeviceCtx DeviceContext) (DeviceContext, error)

DevicePastSeeding returns a device context if a model assertion is available and the device is seeded, at that point the device store is known and seeding done. Otherwise it returns a ChangeConflictError about being too early unless a pre-provided DeviceContext is passed in. It will again return a conflict error during remodeling unless the providedDeviceCtx is for it.

type Flags

type Flags struct {
	// DevMode switches confinement to non-enforcing mode.
	DevMode bool `json:"devmode,omitempty"`
	// JailMode is set when the user has requested confinement
	// always be enforcing, even if the snap requests otherwise.
	JailMode bool `json:"jailmode,omitempty"`
	// Classic is set when the user has consented to install a snap with
	// classic confinement and the snap declares that confinement.
	Classic bool `json:"classic,omitempty"`
	// TryMode is set for snaps installed to try directly from a local directory.
	TryMode bool `json:"trymode,omitempty"`

	// Revert flags the SnapSetup as coming from a revert
	Revert bool `json:"revert,omitempty"`

	// RemoveSnapPath is used via InstallPath to flag that the file passed in is
	// temporary and should be removed
	RemoveSnapPath bool `json:"remove-snap-path,omitempty"`

	// IgnoreValidation is set when the user requested as one-off
	// to ignore refresh control validation.
	IgnoreValidation bool `json:"ignore-validation,omitempty"`

	// IgnoreRunning is set to indicate that running apps or hooks should be
	// ignored.
	IgnoreRunning bool `json:"ignore-running,omitempty"`

	// Required is set to mark that a snap is required
	// and cannot be removed
	Required bool `json:"required,omitempty"`

	// SkipConfigure is used with InstallPath to flag that creating a task
	// running the configure hook should be skipped.
	SkipConfigure bool `json:"skip-configure,omitempty"`

	// SkipKernelExtraction is used with InstallPath to flag that the
	// kernel extraction should be skipped. This is useful during seeding.
	SkipKernelExtraction bool `json:"skip-kernel-extraction,omitempty"`

	// Unaliased is set to request that no automatic aliases are created
	// installing the snap.
	Unaliased bool `json:"unaliased,omitempty"`

	// Amend allows refreshing out of a snap unknown to the store
	// and into one that is known.
	Amend bool `json:"amend,omitempty"`

	// IsAutoRefresh is true if the snap is currently auto-refreshed
	IsAutoRefresh bool `json:"is-auto-refresh,omitempty"`

	// NoReRefresh prevents refresh from adding epoch-hopping
	// re-refresh tasks. This allows refresh to work offline, as
	// long as refresh assets are cached.
	NoReRefresh bool `json:"no-rerefresh,omitempty"`

	// RequireTypeBase is set to mark that a snap needs to be of type: base,
	// otherwise installation fails.
	RequireTypeBase bool `json:"require-base-type,omitempty"`

	// ApplySnapDevMode overrides allowing a snap to be installed if it is in
	// devmode confinement. This is set to true for currently only UC20 model
	// grades dangerous for all snaps during first boot, where we always allow
	// devmode snaps to be installed, and installed with devmode confinement
	// turned on.
	// This may eventually be set for specific snaps mentioned in the model
	// assertion for non-dangerous grade models too.
	ApplySnapDevMode bool `json:"apply-snap-devmode,omitempty"`
}

Flags are used to pass additional flags to operations and to keep track of snap modes.

func (Flags) DevModeAllowed

func (f Flags) DevModeAllowed() bool

DevModeAllowed returns whether a snap can be installed with devmode confinement (either set or overridden).

func (Flags) ForSnapSetup

func (f Flags) ForSnapSetup() Flags

ForSnapSetup returns a copy of the Flags with the flags that we don't need in SnapSetup set to false (so they're not serialized).

type GateAutoRefreshAction

type GateAutoRefreshAction int

gateAutoRefreshAction represents the action executed by snapctl refresh --hold or --proceed and stored in the context of gate-auto-refresh hook.

const (
	GateAutoRefreshProceed GateAutoRefreshAction = iota
	GateAutoRefreshHold
)

type HoldDurationError

type HoldDurationError struct {
	Err          error
	DurationLeft time.Duration
}

HoldDurationError contains the that error prevents requested hold, along with hold time that's left (if any).

func (*HoldDurationError) Error

func (h *HoldDurationError) Error() string

type HoldError

type HoldError struct {
	SnapsInError map[string]HoldDurationError
}

HoldError contains the details of snaps that cannot to be held.

func (*HoldError) Error

func (h *HoldError) Error() string

type InsufficientSpaceError

type InsufficientSpaceError struct {
	// Path is the filesystem path checked for available disk space
	Path string
	// Snaps affected by the failing operation
	Snaps []string
	// Kind of the change that failed
	ChangeKind string
	// Message is optional, otherwise one is composed from the other information
	Message string
}

InsufficientSpaceError represents an error where there is not enough disk space to perform an operation.

func (*InsufficientSpaceError) Error

func (e *InsufficientSpaceError) Error() string

type LinkSnapParticipant

type LinkSnapParticipant interface {
	// SnapLinkageChanged is called when a snap is linked or unlinked.
	// The error is only logged and does not stop the task it is used from.
	SnapLinkageChanged(st *state.State, instanceName string) error
}

LinkSnapParticipant is an interface for interacting with snap link/unlink operations.

Unlike the interface for a task handler, only one notification method is used. The method notifies a participant that linkage of a snap has changed. This method is invoked in link-snap, unlink-snap, the undo path of those methods and the undo handler for link-snap.

In all cases it is invoked after all other operations are completed but before the task completes.

type Policy

type Policy interface {
	// CanRemove verifies that a snap can be removed.
	// If rev is not unset, check for removing only that revision.
	CanRemove(st *state.State, snapst *SnapState, rev snap.Revision, dev boot.Device) error
}

Policy encapsulates behaviour that varies with the details of a snap installation, like the model assertion or the type of snap involved in an operation. Rather than have a forest of `if`s looking at type, model, etc, we move it to Policy and look it up.

type RemoveFlags

type RemoveFlags struct {
	// Remove the snap without creating snapshot data
	Purge bool
}

RemoveFlags are used to pass additional flags to the Remove operation.

type RevisionOptions

type RevisionOptions struct {
	Channel     string
	Revision    snap.Revision
	CohortKey   string
	LeaveCohort bool
}

RevisionOptions control the selection of a snap revision.

type SnapManager

type SnapManager struct {
	// contains filtered or unexported fields
}

SnapManager is responsible for the installation and removal of snaps.

func Manager

func Manager(st *state.State, runner *state.TaskRunner) (*SnapManager, error)

Manager returns a new snap manager.

func (*SnapManager) CanStandby

func (m *SnapManager) CanStandby() bool

func (*SnapManager) EffectiveRefreshHold

func (m *SnapManager) EffectiveRefreshHold() (time.Time, error)

EffectiveRefreshHold returns the time until to which refreshes are held if refresh.hold configuration is set and accounting for the max postponement since the last refresh. The caller should be holding the state lock.

func (*SnapManager) Ensure

func (m *SnapManager) Ensure() error

Ensure implements StateManager.Ensure.

func (*SnapManager) EnsureAutoRefreshesAreDelayed

func (m *SnapManager) EnsureAutoRefreshesAreDelayed(delay time.Duration) ([]*state.Change, error)

EnsureAutoRefreshesAreDelayed will delay refreshes for the specified amount of time, as well as return any active auto-refresh changes that are currently not ready so that the client can wait for those.

func (*SnapManager) LastRefresh

func (m *SnapManager) LastRefresh() (time.Time, error)

LastRefresh returns the time the last snap update. The caller should be holding the state lock.

func (*SnapManager) NextRefresh

func (m *SnapManager) NextRefresh() time.Time

NextRefresh returns the time the next update of the system's snaps will be attempted. The caller should be holding the state lock.

func (*SnapManager) RefreshSchedule

func (m *SnapManager) RefreshSchedule() (string, bool, error)

RefreshSchedule returns the current refresh schedule as a string suitable for display to a user and a flag indicating whether the schedule is a legacy one. The caller should be holding the state lock.

func (*SnapManager) StartUp

func (m *SnapManager) StartUp() error

StartUp implements StateStarterUp.Startup.

func (*SnapManager) SyncCookies

func (m *SnapManager) SyncCookies(st *state.State) error

SyncCookies creates snap cookies for snaps that are missing them (may be the case for snaps installed before the feature of running snapctl outside of hooks was introduced, leading to a warning from snap-confine). It is the caller's responsibility to lock state before calling this function.

type SnapNeedsClassicError

type SnapNeedsClassicError struct {
	Snap string
}

func (*SnapNeedsClassicError) Error

func (e *SnapNeedsClassicError) Error() string

type SnapNeedsClassicSystemError

type SnapNeedsClassicSystemError struct {
	Snap string
}

func (*SnapNeedsClassicSystemError) Error

type SnapNeedsDevModeError

type SnapNeedsDevModeError struct {
	Snap string
}

func (*SnapNeedsDevModeError) Error

func (e *SnapNeedsDevModeError) Error() string

type SnapNotClassicError

type SnapNotClassicError struct {
	Snap string
}

func (*SnapNotClassicError) Error

func (e *SnapNotClassicError) Error() string

type SnapSetup

type SnapSetup struct {
	// FIXME: rename to RequestedChannel to convey the meaning better
	Channel string    `json:"channel,omitempty"`
	UserID  int       `json:"user-id,omitempty"`
	Base    string    `json:"base,omitempty"`
	Type    snap.Type `json:"type,omitempty"`
	// PlugsOnly indicates whether the relevant revisions for the
	// operation have only plugs (#plugs >= 0), and absolutely no
	// slots (#slots == 0).
	PlugsOnly bool `json:"plugs-only,omitempty"`

	CohortKey string `json:"cohort-key,omitempty"`

	// FIXME: implement rename of this as suggested in
	//  https://github.com/snapcore/snapd/pull/4103#discussion_r169569717
	//
	// Prereq is a list of snap-names that need to get installed
	// together with this snap. Typically used when installing
	// content-snaps with default-providers.
	Prereq []string `json:"prereq,omitempty"`

	Flags

	SnapPath string `json:"snap-path,omitempty"`

	DownloadInfo *snap.DownloadInfo `json:"download-info,omitempty"`
	SideInfo     *snap.SideInfo     `json:"side-info,omitempty"`

	// InstanceKey is set by the user during installation and differs for
	// each instance of given snap
	InstanceKey string `json:"instance-key,omitempty"`
	// contains filtered or unexported fields
}

SnapSetup holds the necessary snap details to perform most snap manager tasks.

func TaskSnapSetup

func TaskSnapSetup(t *state.Task) (*SnapSetup, error)

TaskSnapSetup returns the SnapSetup with task params hold by or referred to by the task.

func (*SnapSetup) InstanceName

func (snapsup *SnapSetup) InstanceName() string

func (*SnapSetup) MountDir

func (snapsup *SnapSetup) MountDir() string

func (*SnapSetup) MountFile

func (snapsup *SnapSetup) MountFile() string

func (*SnapSetup) Revision

func (snapsup *SnapSetup) Revision() snap.Revision

func (*SnapSetup) SnapName

func (snapsup *SnapSetup) SnapName() string

type SnapState

type SnapState struct {
	SnapType string           `json:"type"` // Use Type and SetType
	Sequence []*snap.SideInfo `json:"sequence"`
	Active   bool             `json:"active,omitempty"`

	// LastActiveDisabledServices is a list of services that were disabled in
	// this snap when it was last active - i.e. when it was disabled, before
	// it was reverted, or before a refresh happens.
	// It is set during unlink-snap and unlink-current-snap and reset during
	// link-snap since it is only meant to be saved when snapd needs to remove
	// systemd units.
	// Note that to handle potential service renames, only services that exist
	// in the snap are removed from this list on link-snap, so that we can
	// remember services that were disabled in another revision and then renamed
	// or otherwise removed from the snap in a future refresh.
	LastActiveDisabledServices []string `json:"last-active-disabled-services,omitempty"`

	// tracking services enabled and disabled by hooks
	ServicesEnabledByHooks  []string `json:"services-enabled-by-hooks,omitempty"`
	ServicesDisabledByHooks []string `json:"services-disabled-by-hooks,omitempty"`

	// Current indicates the current active revision if Active is
	// true or the last active revision if Active is false
	// (usually while a snap is being operated on or disabled)
	Current         snap.Revision `json:"current"`
	TrackingChannel string        `json:"channel,omitempty"`
	Flags
	// aliases, see aliasesv2.go
	Aliases             map[string]*AliasTarget `json:"aliases,omitempty"`
	AutoAliasesDisabled bool                    `json:"auto-aliases-disabled,omitempty"`
	AliasesPending      bool                    `json:"aliases-pending,omitempty"`

	// UserID of the user requesting the install
	UserID int `json:"user-id,omitempty"`

	// InstanceKey is set by the user during installation and differs for
	// each instance of given snap
	InstanceKey string `json:"instance-key,omitempty"`
	CohortKey   string `json:"cohort-key,omitempty"`

	// RefreshInhibitedime records the time when the refresh was first
	// attempted but inhibited because the snap was busy. This value is
	// reset on each successful refresh.
	RefreshInhibitedTime *time.Time `json:"refresh-inhibited-time,omitempty"`

	// LastRefreshTime records the time when the snap was last refreshed.
	LastRefreshTime *time.Time `json:"last-refresh-time,omitempty"`
}

SnapState holds the state for a snap installed in the system.

func (*SnapState) Block

func (snapst *SnapState) Block() []snap.Revision

Block returns revisions that should be blocked on refreshes, computed from Sequence[currentRevisionIndex+1:].

func (*SnapState) CurrentInfo

func (snapst *SnapState) CurrentInfo() (*snap.Info, error)

CurrentInfo returns the information about the current active revision or the last active revision (if the snap is inactive). It returns the ErrNoCurrent error if snapst.Current is unset.

func (*SnapState) CurrentSideInfo

func (snapst *SnapState) CurrentSideInfo() *snap.SideInfo

CurrentSideInfo returns the side info for the revision indicated by snapst.Current in the snap revision sequence if there is one.

func (*SnapState) InstanceName

func (snapst *SnapState) InstanceName() string

func (*SnapState) IsInstalled

func (snapst *SnapState) IsInstalled() bool

IsInstalled returns whether the snap is installed, i.e. snapst represents an installed snap with Current revision set.

func (*SnapState) LastIndex

func (snapst *SnapState) LastIndex(revision snap.Revision) int

LastIndex returns the last index of the given revision in the snapst.Sequence

func (*SnapState) LocalRevision

func (snapst *SnapState) LocalRevision() snap.Revision

LocalRevision returns the "latest" local revision. Local revisions start at -1 and are counted down.

func (*SnapState) SetTrackingChannel

func (snapst *SnapState) SetTrackingChannel(s string) error

func (*SnapState) SetType

func (snapst *SnapState) SetType(typ snap.Type)

SetType records the type of the snap.

func (*SnapState) Type

func (snapst *SnapState) Type() (snap.Type, error)

Type returns the type of the snap or an error. Should never error if Current is not nil.

type StoreService

type StoreService interface {
	EnsureDeviceSession() (*auth.DeviceState, error)

	SnapInfo(ctx context.Context, spec store.SnapSpec, user *auth.UserState) (*snap.Info, error)
	SnapExists(ctx context.Context, spec store.SnapSpec, user *auth.UserState) (naming.SnapRef, *channel.Channel, error)
	Find(ctx context.Context, search *store.Search, user *auth.UserState) ([]*snap.Info, error)

	SnapAction(ctx context.Context, currentSnaps []*store.CurrentSnap, actions []*store.SnapAction, assertQuery store.AssertionQuery, user *auth.UserState, opts *store.RefreshOptions) ([]store.SnapActionResult, []store.AssertionResult, error)

	Sections(ctx context.Context, user *auth.UserState) ([]string, error)
	WriteCatalogs(ctx context.Context, names io.Writer, adder store.SnapAdder) error

	Download(context.Context, string, string, *snap.DownloadInfo, progress.Meter, *auth.UserState, *store.DownloadOptions) error
	DownloadStream(context.Context, string, *snap.DownloadInfo, int64, *auth.UserState) (r io.ReadCloser, status int, err error)

	Assertion(assertType *asserts.AssertionType, primaryKey []string, user *auth.UserState) (asserts.Assertion, error)
	SeqFormingAssertion(assertType *asserts.AssertionType, sequenceKey []string, sequence int, user *auth.UserState) (asserts.Assertion, error)
	DownloadAssertions([]string, *asserts.Batch, *auth.UserState) error

	SuggestedCurrency() string
	Buy(options *client.BuyOptions, user *auth.UserState) (*client.BuyResult, error)
	ReadyToBuy(*auth.UserState) error
	ConnectivityCheck() (map[string]bool, error)
	CreateCohorts(context.Context, []string) (map[string]string, error)

	LoginUser(username, password, otp string) (string, string, error)
	UserInfo(email string) (userinfo *store.User, err error)
}

A StoreService can find, list available updates and download snaps.

func Store

func Store(st *state.State, deviceCtx DeviceContext) StoreService

Store returns the store service provided by the optional device context or the one used by the snapstate package if the former has no override.

Directories

Path Synopsis
Package backend implements the low-level primitives to manage the snaps and their installation on disk.
Package backend implements the low-level primitives to manage the snaps and their installation on disk.
Package policy implements fine grained decision-making for snapstate
Package policy implements fine grained decision-making for snapstate

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL