snap

Representations of the system’s Snaps, and abstractions around managing them.

The snap package provides convenience methods for listing, installing, refreshing, and removing Snap packages, in addition to setting and getting configuration options for them.

In the snap package, SnapCache creates a dict-like mapping of Snap objects when instantiated. Installed snaps are fully populated, and available snaps are lazily-loaded upon request. This module relies on an installed and running snapd daemon to perform operations over the snapd HTTP API.

SnapCache objects can be used to install or modify nnap packages by name in a manner similar to using the snap command from the commandline.

An example of adding Juju to the system with SnapCache and setting a config value:

try:
    cache = snap.SnapCache()
    juju = cache["juju"]

    if not juju.present:
        juju.ensure(snap.SnapState.Latest, channel="beta")
        juju.set({"some.key": "value", "some.key2": "value2"})
except snap.SnapError as e:
    logger.error("An exception occurred when installing charmcraft. Reason: %s", e.message)

In addition, the snap module provides “bare” methods which can act on Snap packages as simple function calls. add, remove, and ensure are provided, as well as add_local for installing directly from a local .snap file. These return Snap objects.

As an example of installing several Snaps and checking details:

try:
    nextcloud, charmcraft = snap.add(["nextcloud", "charmcraft"])
    if nextcloud.get("mode") != "production":
        nextcloud.set({"mode": "production"})
except snap.SnapError as e:
    logger.error("An exception occurred when installing snaps. Reason: %s" % e.message)
exception Error(message: str = '', *args: object)

Bases: Exception

Base class of most errors raised by this library.

property name: str

Return a string representation of the model plus class.

class MetaCache

Bases: type

MetaCache class used for initialising the snap cache.

__getitem__(name: str) Snap

Snap cache getter.

property cache: SnapCache

Property for returning the snap cache.

class Snap(
name: str,
state: SnapState,
channel: str,
revision: str,
confinement: str,
apps: list[dict[str, dict[str, dict[str, JSONType] | list[JSONType] | _JSONLeaf] | list[dict[str, JSONType] | list[JSONType] | _JSONLeaf] | str | int | float | bool]] | None = None,
cohort: str | None = None,
*,
version: str | None = None,
)

Bases: object

Represents a snap package and its properties.

Snap exposes the following properties about a snap:
  • name: the name of the snap

  • state: a SnapState representation of its install status

  • channel: “stable”, “candidate”, “beta”, and “edge” are common

  • revision: a string representing the snap’s revision

  • confinement: “classic”, “strict”, or “devmode”

  • version: a string representing the snap’s version, if set by the snap author

alias(application: str, alias: str | None = None) None

Create an alias for a given application.

Parameters:
  • application – application to get an alias.

  • alias – (optional) name of the alias; if not provided, the application name is used.

property apps: list[dict[str, dict[str, dict[str, JSONType] | list[JSONType] | _JSONLeaf] | list[dict[str, JSONType] | list[JSONType] | _JSONLeaf] | str | int | float | bool]]

Returns (if any) the installed apps of the snap.

property channel: str

Returns the channel for a snap.

property confinement: str

Returns the confinement for a snap.

connect(
plug: str,
service: str | None = None,
slot: str | None = None,
) None

Connect a plug to a slot.

Parameters:
  • plug (str) – the plug to connect

  • service (str) – (optional) the snap service name to plug into

  • slot (str) – (optional) the snap service slot to plug in to

Raises:

SnapError if there is a problem encountered

ensure(
state: SnapState,
classic: bool = False,
devmode: bool = False,
channel: str | None = None,
cohort: str | None = None,
revision: str | int | None = None,
)

Ensure that a snap is in a given state.

Parameters:
  • state – a SnapState to reconcile to.

  • classic – an (Optional) boolean indicating whether classic confinement should be used

  • devmode – an (Optional) boolean indicating whether devmode confinement should be used

  • channel – the channel to install from

  • cohort – optional. Specify the key of a snap cohort.

  • revision – optional. the revision of the snap to install/refresh

While both channel and revision could be specified, the underlying snap install/refresh command will determine which one takes precedence (revision at this time)

Raises:

SnapError if an error is encountered

get(key: str | None, *, typed: bool = False) JSONType | str

Fetch snap configuration values.

Parameters:
  • key – the key to retrieve. Default to retrieve all values for typed=True.

  • typed – set to True to retrieve typed values (set with typed=True). Default is to return a string.

property held: bool

Report whether the snap has a hold.

hold(duration: timedelta | None = None) None

Add a refresh hold to a snap.

Parameters:

duration – duration for the hold, or None (the default) to hold this snap indefinitely.

property latest: bool

Report whether the snap is the most recent version.

logs(
services: list[str] | None = None,
num_lines: int | Literal['all'] = 10,
) str

Fetch a snap services’ logs.

Parameters:
  • services – individual snap services to show logs from. Includes all by default.

  • num_lines – number of log lines to return, or ‘all’. Returns 10 by default.

property name: str

Returns the name of the snap.

property present: bool

Report whether or not a snap is present.

restart(services: list[str] | None = None, reload: bool = False) None

Restarts a snap’s services.

Parameters:
  • services (list) – (optional) list of individual snap services to restart. (otherwise all)

  • reload (bool) – (optional) flag to use the service reload command, if available. Default False

property revision: str

Returns the revision for a snap.

property services: dict[str, SnapServiceDict]

Returns (if any) the installed services of the snap.

set(
config: Mapping[str, Mapping[str, Mapping[str, JSONAble] | Sequence[JSONAble] | _JSONLeaf | None] | Sequence[Mapping[str, JSONAble] | Sequence[JSONAble] | _JSONLeaf | None] | str | int | float | bool | None],
*,
typed: bool = False,
) None

Set a snap configuration value.

Parameters:
  • config – a dictionary containing keys and values specifying the config to set.

  • typed – set to True to convert all values in the config into typed values while configuring the snap (set with typed=True). Default is not to convert.

start(services: list[str] | None = None, enable: bool = False) None

Start a snap’s services.

Parameters:
  • services (list) – (optional) list of individual snap services to start (otherwise all)

  • enable (bool) – (optional) flag to enable snap services on start. Default false

property state: SnapState

Report the current snap state.

stop(services: list[str] | None = None, disable: bool = False) None

Stop a snap’s services.

Parameters:
  • services (list) – (optional) list of individual snap services to stop (otherwise all)

  • disable (bool) – (optional) flag to disable snap services on stop. Default False

unhold() None

Remove the refresh hold of a snap.

unset(key: str) str

Unset a snap configuration value.

Parameters:

key – the key to unset

property version: str | None

Returns the version for a snap.

exception SnapAPIError(
body: Mapping[str, Mapping[str, Mapping[str, JSONAble] | Sequence[JSONAble] | _JSONLeaf | None] | Sequence[Mapping[str, JSONAble] | Sequence[JSONAble] | _JSONLeaf | None] | str | int | float | bool | None],
code: int,
status: str,
message: str,
)

Bases: Error

Raised when an HTTP API error occurs talking to the Snapd server.

class SnapCache

Bases: Mapping[str, Snap]

An abstraction to represent installed/available packages.

When instantiated, SnapCache iterates through the list of installed snaps using the snapd HTTP API, and a list of available snaps by reading the filesystem to populate the cache. Information about available snaps is lazily-loaded from the snapd API when requested.

__contains__(key: object) bool

Check if a given snap is in the cache.

__getitem__(snap_name: str) Snap

Return either the installed version or latest version for a given snap.

__iter__() Iterable[Snap | None]

Provide iterator for the snap cache.

__len__() int

Report number of items in the snap cache.

property snapd_installed: bool

Check whether snapd has been installed on the system.

class SnapClient(
socket_path: str = '/run/snapd.socket',
opener: OpenerDirector | None = None,
base_url: str = 'http://localhost/v2/',
timeout: float = 30.0,
)

Bases: object

Snapd API client to talk to HTTP over UNIX sockets.

In order to avoid shelling out and/or involving sudo in calling the snapd API, use a wrapper based on the Pebble Client, trimmed down to only the utility methods needed for talking to snapd.

get_installed_snap_apps(
name: str,
) list[dict[str, dict[str, dict[str, JSONType] | list[JSONType] | _JSONLeaf] | list[dict[str, JSONType] | list[JSONType] | _JSONLeaf] | str | int | float | bool]]

Query the snap server for apps belonging to a named, currently installed snap.

get_installed_snaps() list[dict[str, dict[str, dict[str, JSONType] | list[JSONType] | _JSONLeaf] | list[dict[str, JSONType] | list[JSONType] | _JSONLeaf] | str | int | float | bool]]

Get information about currently installed snaps.

get_snap_information(
name: str,
) dict[str, dict[str, dict[str, JSONType] | list[JSONType] | _JSONLeaf] | list[dict[str, JSONType] | list[JSONType] | _JSONLeaf] | str | int | float | bool]

Query the snap server for information about single snap.

exception SnapError(message: str = '', *args: object)

Bases: Error

Raised when there’s an error running snap control commands.

exception SnapNotFoundError(message: str = '', *args: object)

Bases: Error

Raised when a requested snap is not known to the system.

class SnapService(
daemon: str | None = None,
daemon_scope: str | None = None,
enabled: bool = False,
active: bool = False,
activators: list[str] | None = None,
**kwargs: Unpack[_SnapServiceKwargsDict],
)

Bases: object

Data wrapper for snap services.

as_dict() SnapServiceDict

Return instance representation as dict.

class SnapServiceDict

Bases: TypedDict

Dictionary representation returned by SnapService.as_dict.

__optional_keys__ = frozenset({})
__required_keys__ = frozenset({'activators', 'active', 'daemon', 'daemon_scope', 'enabled'})
__total__ = True
daemon: str | None
daemon_scope: str | None
enabled: bool
active: bool
activators: list[str]
class SnapState(*values)

Bases: Enum

The state of a snap on the system or in the cache.

Present = 'present'
Absent = 'absent'
Latest = 'latest'
Available = 'available'
add(*args: _P.args, **kwargs: _P.kwargs) _T
ensure(*args: _P.args, **kwargs: _P.kwargs) _T
hold_refresh(days: int = 90, forever: bool = False) None

Set the system-wide snap refresh hold.

Parameters:
  • days – number of days to hold system refreshes for. Maximum 90. Set to zero to remove hold.

  • forever – if True, will set a hold forever.

install_local(
filename: str,
classic: bool = False,
devmode: bool = False,
dangerous: bool = False,
) Snap

Perform a snap operation.

Parameters:
  • filename – the path to a local .snap file to install

  • classic – whether to use classic confinement

  • devmode – whether to use devmode confinement

  • dangerous – whether –dangerous should be passed to install snaps without a signature

Raises:

SnapError if there is a problem encountered

remove(*args: _P.args, **kwargs: _P.kwargs) _T