snap

Opinionated library for performing snap operations, targeted at use in charm code.

Use ensure or ensure_revision to ensure that a snap is installed.

Manually manage snap installation with install, refresh, and remove. Use info to query the current state of an installed snap.

Also manage:

  • Automatic refreshes with hold and unhold.

  • Services with start, stop, and restart.

  • Config with config_get, config_set, and config_unset.

  • Connections between snaps with connect and disconnect.

  • Application aliases with alias and unalias.

Exceptions

All functions will raise a Error subclass if the snapd API returns an error response.

Functions will raise specific subclasses where possible to allow callers to handle logical errors. Check the documentation for each function for details on which exceptions it may raise.

The APIError subclass will be raised if the snapd API returns a malformed response. Callers will not be able to resolve this error directly, but may want to catch it for logging, or to trigger retries if the error may be transient. If retries are not successful, user intervention may be required.

A ConnectionError indicates a failure to connect to the snapd socket at all. In this case something is badly wrong with the system, and user intervention is almost certainly required.

exception APIError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: Error

Raised when the snapd API returns an error response.

exception AppNotFoundError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: APIError

Raised via the API when a specified app is not found within an installed snap.

exception BadResponseError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: Error

Raised manually when the snapd API returns a response we don’t understand.

Callers will not be able to resolve this error directly, but may want to catch it for logging, or to trigger retries. If retries are not successful, user intervention may be required.

exception ChangeError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: APIError

Raised when a snap change results in an error or has an unexpected status.

exception ChannelNotAvailableError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: APIError

Raised via the API when no snap revision is available on the specified channel.

exception ConnectionError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: Error, ConnectionError

Raised when a connection to the snapd socket fails.

This typically indicates that snapd is not installed or running.

exception Error(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: Exception

Base class for all library errors, not raised directly.

Parameters:
  • message – Typically the ‘message’ field from a snapd API response.

  • kind – The ‘kind’ field from a snapd API response, used to derive the specific error type. Manually constructed errors have the kind ‘charmlibs-snap’.

  • value – The ‘value’ field from a snapd API response, which may contain additional details. Almost always a string, but can be any JSON value.

  • status_code – The HTTP status code from the snapd API response, if applicable. Stored privately for logging and debugging, not part of the public error API.

  • status – The ‘status’ field from a snapd API response, if applicable. Stored privately for logging and debugging, not part of the public error API.

property message: str

The error message, typically from the snapd API response.

property kind: str

The error kind, typically from the snapd API response.

property value: object

The error value, typically from the snapd API response.

Currently a string, but future library versions may return any object subtype.

class Info(
name: str,
classic: bool,
channel: str,
revision: int | str,
version: str,
hold: datetime | str | None,
)

Bases: object

property name: str
property classic: bool
property channel: str
property revision: str
property version: str
property hold: datetime | None
class LogEntry(timestamp: datetime.datetime, sid: str, pid: int, message: str)

Bases: object

A single snap log entry.

property timestamp: datetime.datetime

The timestamp of the log entry as a datetime object.

property message: str

The log message itself.

property sid: str

The syslog identifier.

The name the process registered with syslog, typically the snap service name.

property pid: int

The process ID.

exception NeedsClassicError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: APIError

Raised via the API if classic is not specified for a classic confinement snap.

This can occur for a snap install or refresh.

exception NotFoundError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: APIError

Raised via the API when a snap is not found in the store.

exception NotInstalledError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: APIError

Raised via the API when a snap is not installed on the system.

exception OptionNotFoundError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: APIError

Raised via the API when the specified snap config option is not found.

OptionNotFoundError.value looks like "{'SnapName': 'hello-world', 'Key': 'foo'}".

exception RevisionNotAvailableError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: APIError

Raised via the API when the specified snap revision is not available.

exception TimeoutError(
message: str,
*,
kind: str,
value: object,
status_code: int | None = None,
status: str | None = None,
)

Bases: Error, TimeoutError

Raised when snapd does not respond to a request in time.

This typically indicates that snapd is waiting on the snap store, which may indicate a transient issue with the store or a problem with the system’s network connection. Callers may want to catch this for retry logic or to surface a user-friendly message.

ensure(
snap: str,
channel: str | None = None,
*,
classic: bool = False,
update: bool = True,
) object

Ensure the snap is installed and up-to-date on the specified channel.

The action taken depends on the current state of the snap:

  • If the snap is not installed, it will be installed on the specified channel (defaulting to latest/stable).

  • If the snap is installed on a different channel, it will be refreshed to the specified channel.

  • If the snap is already installed on the specified channel (or installed at all if no channel is specified), it will be refreshed only if update = True (default).

Parameters:
  • snap – The name of the snap to install or update.

  • channel – The channel to track, for example latest/edge. If None (default), the snap is installed from latest/stable when not already installed, and an already-installed snap’s channel is left unchanged.

  • classic – If True, install the snap with classic confinement. Required for snaps that use classic confinement.

  • update – If True (default), refresh the snap when it is already installed on the requested channel. If False, leave an already-correct snap untouched.

Returns:

A truthy value if the snap was installed or updated, or a falsy value otherwise. Not guaranteed to be an actual bool.

Raises:
  • NotFoundError – If the snap does not exist in the store.

  • NeedsClassicError – If the snap requires classic=True.

  • ChannelNotAvailableError – If the channel is invalid or unavailable.

  • ChangeError – If the install or refresh fails after starting (for example, a hook errors).

  • Error – (or a subtype) if the snap could not be installed or refreshed for another reason.

ensure_revision(
snap: str,
revision: int | str,
*,
classic: bool = False,
) object

Ensure the snap is installed at the specified revision.

Parameters:
  • snap – The name of the snap to install or update.

  • revision – The revision to ensure is installed, as an int or string.

  • classic – If True, install the snap with classic confinement. Required for snaps that use classic confinement.

Returns:

A truthy value if the snap was installed or updated, or a falsy value otherwise. Not guaranteed to be an actual bool.

Raises:
  • NotFoundError – If the snap does not exist in the store.

  • RevisionNotAvailableError – If the revision does not exist.

  • NeedsClassicError – If the snap requires classic=True.

  • ChangeError – If the install or refresh fails after starting (for example, a hook errors).

  • Error – (or a subtype) if the snap could not be installed or refreshed for another reason.

hold(
snap: str,
duration: timedelta | int | float | None = None,
) None

Hold a snap to prevent it from being automatically refreshed.

Does not prevent manual refreshes.

Parameters:
  • snap – The name of the snap to hold.

  • duration – How long to hold automatic refreshes for, measured from now. May be a datetime.timedelta, or a number of seconds as an int or float. If None (default), the snap is held indefinitely.

Raises:
info(snap: str) Info

Get information about an installed snap.

This function implements the semantics of the snap list command, restricted to a single snap.

Parameters:

snap – the name of the snap.

Returns:

An Info object with information about the snap.

Raises:
  • NotFoundError – if the snap is not installed.

  • Error – (or a subtype) if the information could not be retrieved for another reason.

install(
snap: str,
*,
channel: str | None = None,
revision: int | str | None = None,
classic: bool = False,
) object

Install a snap.

Parameters:
  • snap – The name of the snap to install.

  • channel – The channel to install from, for example latest/edge. Mutually exclusive with revision. If neither is given, snapd installs from latest/stable.

  • revision – The revision to install, as an int or string. Mutually exclusive with channel.

  • classic – If True, install the snap with classic confinement. Required for snaps that use classic confinement.

Returns:

A truthy value if the snap was installed, or a falsy value if it was already installed. Not guaranteed to be an actual bool.

Raises:
logs(*snaps: str, limit: int | None = 10) list[LogEntry]

Retrieve recent log entries for one or more snaps.

Log entries are returned in chronological order: oldest first, newest last.

Parameters:
  • snaps – Snap names to retrieve logs for. If omitted, returns system-wide snap logs.

  • limit – Maximum number of log entries to return. Must be a positive integer, or None to retrieve all available log entries (equivalent to snap logs -n all).

Returns:

A list of LogEntry objects, ordered oldest first. The list may contain fewer entries than limit if fewer are available. Malformed entries returned by snapd are skipped (and logged as warnings) rather than raising.

Raises:
refresh(
snap: str,
channel: str | None = None,
*,
revision: int | str | None = None,
) object

Refresh a snap.

Parameters:
  • snap – The name of the snap to refresh.

  • channel – The channel to refresh to, for example latest/edge. Mutually exclusive with revision. If neither is given, the snap is refreshed on its current channel.

  • revision – The revision to refresh to, as an int or string. Mutually exclusive with channel.

Returns:

A truthy value if the snap was refreshed, or a falsy value if no updates were available. Not guaranteed to be an actual bool.

Raises:
  • ValueError – if both channel and revision are specified.

  • RevisionNotAvailableError – if the specified revision is not available.

  • ChannelNotAvailableError – if the specified channel is not available.

  • ChangeError – if the refresh fails after starting (for example, a refresh hook errors).

  • Error – (or a subtype) if the snap could not be refreshed for another reason.

remove(snap: str, *, purge: bool = False) object

Remove a snap.

Parameters:
  • snap – The name of the snap to remove.

  • purge – If True, remove the snap without saving a snapshot of its data.

Returns:

A truthy value if the snap was removed, or a falsy value if it was not installed. Not guaranteed to be an actual bool.

Raises:
  • ChangeError – if the removal fails after starting (for example, a remove hook errors).

  • Error – (or a subtype) if the snap could not be removed as requested.

restart(snap: str, *services: str) None

Restart snap services.

Parameters:
  • snap – The name of the snap whose services to restart.

  • services – Names of services within the snap to restart. If omitted, all of the snap’s services are restarted.

Raises:
  • AppNotFoundError – if the snap is not installed or the service is not found.

  • ChangeError – if the change fails (for example, the service fails to restart).

start(snap: str, *services: str, enable: bool = False) None

Start snap services.

Parameters:
  • snap – The name of the snap whose services to start.

  • services – Names of services within the snap to start. If omitted, all of the snap’s services are started.

  • enable – If True, also enable the services to start automatically at boot.

Raises:
  • AppNotFoundError – if the snap is not installed or the service is not found.

  • ChangeError – if the change fails (for example, the service fails to start).

stop(snap: str, *services: str, disable: bool = False) None

Stop snap services.

Parameters:
  • snap – The name of the snap whose services to stop.

  • services – Names of services within the snap to stop. If omitted, all of the snap’s services are stopped.

  • disable – If True, also disable the services from starting automatically at boot.

Raises:
  • AppNotFoundError – if the snap is not installed or the service is not found.

  • ChangeError – if the change fails (for example, the service fails to stop).

unhold(snap: str) None

Unhold a snap to allow it to be refreshed.

Does not raise if the snap is not installed or not held.

Parameters:

snap – The name of the snap to unhold.

Raises:

ChangeError – If the unhold change fails after starting.