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:
Config with
config_get,config_set, andconfig_unset.Connections between snaps with
connectanddisconnect.Application aliases with
aliasandunalias.
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:
ErrorRaised 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:
APIErrorRaised 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:
ErrorRaised 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:
APIErrorRaised 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:
APIErrorRaised 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,ConnectionErrorRaised 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:
ExceptionBase 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.
- class Info(
- name: str,
- classic: bool,
- channel: str,
- revision: int | str,
- version: str,
- hold: datetime | str | None,
Bases:
object
- class LogEntry(timestamp: datetime.datetime, sid: str, pid: int, message: str)¶
Bases:
objectA single snap log entry.
- property timestamp: datetime.datetime¶
The timestamp of the log entry as a datetime object.
- exception NeedsClassicError(
- message: str,
- *,
- kind: str,
- value: object,
- status_code: int | None = None,
- status: str | None = None,
Bases:
APIErrorRaised 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:
APIErrorRaised 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:
APIErrorRaised 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:
APIErrorRaised via the API when the specified snap config option is not found.
OptionNotFoundError.valuelooks like"{'SnapName': 'hello-world', 'Key': 'foo'}".
- exception RevisionNotAvailableError(
- message: str,
- *,
- kind: str,
- value: object,
- status_code: int | None = None,
- status: str | None = None,
Bases:
APIErrorRaised 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,TimeoutErrorRaised 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( ) 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. IfNone(default), the snap is installed fromlatest/stablewhen 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. IfFalse, 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( ) 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( ) 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. IfNone(default), the snap is held indefinitely.
- Raises:
NotFoundError – If the snap is not installed.
ChangeError – If the hold change fails after starting.
- 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( ) 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 withrevision. If neither is given, snapd installs fromlatest/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:
ValueError – if both channel and revision are specified.
NotFoundError – if the snap does not exist in the store.
RevisionNotAvailableError – if the specified revision is not available.
ChannelNotAvailableError – if the specified channel is not available.
NeedsClassicError – if the snap requires classic confinement and
classicis not set.ChangeError – if the install fails after starting (for example, an install hook errors).
Error – (or a subtype) if the snap could not be installed for another reason.
- 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
Noneto retrieve all available log entries (equivalent tosnap logs -n all).
- Returns:
A list of
LogEntryobjects, ordered oldest first. The list may contain fewer entries thanlimitif fewer are available. Malformed entries returned by snapd are skipped (and logged as warnings) rather than raising.- Raises:
ValueError – If
limitis notNoneand is not a positive integer.NotFoundError – If a specified snap is not installed.
AppNotFoundError – If a specified snap has no services.
- refresh( ) 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 withrevision. 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.