Operator Libs Linux

  • By Jon Seager
Channel Revision Published Runs on
latest/stable 2 09 Mar 2023
Ubuntu 22.04
juju deploy operator-libs-linux
Show information

Platform:

Ubuntu
22.04

charms.operator_libs_linux.v2.snap

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

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

In the snap module, SnapCache creates a dict-like mapping of Snap objects at 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 Snap 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. :meth:add, :meth:remove, and :meth:ensure are provided, as well as :meth: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)

Index

class SnapService

Description

Data wrapper for snap services. None

Methods

SnapService. __init__( self , daemon , daemon_scope , enabled: bool , active: bool , activators )

SnapService. as_dict( self )

Description

Return instance representation as dict. None

class MetaCache

Description

MetaCache class used for initialising the snap cache. None

Methods

MetaCache. cache( cls )

Description

Property for returning the snap cache. None

MetaCache. cache( cls , cache )

Description

Setter for the snap cache. None

MetaCache. __getitem__( cls , name )

Description

Snap cache getter. None

class Error

Description

Base class of most errors raised by this library. None

Methods

Error. __repr__( self )

Description

Represent the Error class. None

Error. name( self )

Description

Return a string representation of the model plus class. None

Error. message( self )

Description

Return the message passed as an argument. None

class SnapAPIError

Description

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

Methods

SnapAPIError. __init__( self , body: Dict , code: int , status: str , message: str )

SnapAPIError. __repr__( self )

Description

Represent the SnapAPIError class. None

class SnapState

Description

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

class SnapError

Description

Raised when there's an error running snap control commands. None

class SnapNotFoundError

Description

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

class Snap

Represents a snap package and its properties.

Description

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"

Methods

Snap. __init__( self , name , state: SnapState , channel: str , revision: str , confinement: str , apps , cohort )

Snap. __eq__( self , other )

Description

Equality for comparison. None

Snap. __hash__( self )

Description

Calculate a hash for this snap. None

Snap. __repr__( self )

Description

Represent the object such that it can be reconstructed. None

Snap. __str__( self )

Description

Represent the snap object as a string. None

Snap. get( self , key )

Fetch snap configuration values.

Arguments

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.

Snap. set( self , config )

Set a snap configuration value.

Arguments

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.

Snap. unset( self , key )

Unset a snap configuration value.

Arguments

key

the key to unset

Snap. start( self , services , enable )

Start a snap's services.

Arguments

services (list)

(optional) list of individual snap services to start (otherwise all)

enable (bool)

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

Snap. stop( self , services , disable )

Stop a snap's services.

Arguments

services (list)

(optional) list of individual snap services to stop (otherwise all)

disable (bool)

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

Snap. logs( self , services , num_lines )

Fetch a snap services' logs.

Arguments

services (list)

(optional) list of individual snap services to show logs from (otherwise all)

num_lines (int)

(optional) integer number of log lines to return. Default 10

Snap. connect( self , plug: str , service , slot )

Connect a plug to a slot.

Description

Args: 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

Snap. hold( self , duration )

Add a refresh hold to a snap.

Arguments

duration

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

Snap. unhold( self )

Description

Remove the refresh hold of a snap. None

Snap. alias( self , application: str , alias )

Create an alias for a given application.

Arguments

application

application to get an alias.

alias

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

Snap. restart( self , services , reload )

Restarts a snap's services.

Arguments

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

Snap. name( self )

Description

Returns the name of the snap. None

Snap. ensure( self , state: SnapState , classic , devmode: bool , channel , cohort , revision )

Ensure that a snap is in a given state.

Description

Args: 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

Snap. present( self )

Description

Report whether or not a snap is present. None

Snap. latest( self )

Description

Report whether the snap is the most recent version. None

Snap. state( self )

Description

Report the current snap state. None

Snap. state( self , state: SnapState )

Set the snap state to a given value.

Description

Args: state: a SnapState to reconcile the snap to.

Raises: SnapError if an error is encountered

Snap. revision( self )

Description

Returns the revision for a snap. None

Snap. channel( self )

Description

Returns the channel for a snap. None

Snap. confinement( self )

Description

Returns the confinement for a snap. None

Snap. apps( self )

Description

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

Snap. services( self )

Description

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

Snap. held( self )

Description

Report whether the snap has a hold. None

class SnapClient

Snapd API client to talk to HTTP over UNIX sockets.

Description

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.

Methods

SnapClient. __init__( self , socket_path: str , opener , base_url: str , timeout: float )

Initialize a client instance.

Arguments

socket_path

a path to the socket on the filesystem. Defaults to /run/snap/snapd.socket

opener

specifies an opener for unix socket, if unspecified a default is used

base_url

base url for making requests to the snap client. Defaults to http://localhost/v2/

timeout

timeout in seconds to use when making requests to the API. Default is 30.0s.

SnapClient. get_installed_snaps( self )

Description

Get information about currently installed snaps. None

SnapClient. get_snap_information( self , name: str )

Description

Query the snap server for information about single snap. None

SnapClient. get_installed_snap_apps( self , name: str )

Description

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

class SnapCache

An abstraction to represent installed/available packages.

Description

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.

Methods

SnapCache. __init__( self )

SnapCache. __contains__( self , key: str )

Description

Check if a given snap is in the cache. None

SnapCache. __len__( self )

Description

Report number of items in the snap cache. None

SnapCache. __iter__( self )

Description

Provide iterator for the snap cache. None

SnapCache. __getitem__( self , snap_name: str )

Description

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

SnapCache. snapd_installed( self )

Description

Check whether snapd has been installled on the system. None

def add(
    snap_names,
    state,
    channel,
    classic,
    devmode: bool,
    cohort,
    revision
)

Add a snap to the system.

Description

Args: snap_names: the name or names of the snaps to install state: a string or SnapState representation of the desired state, one of [Present or Latest] channel: an (Optional) channel as a string. Defaults to 'latest' classic: an (Optional) boolean specifying whether it should be added with classic confinement. Default False devmode: an (Optional) boolean specifying whether it should be added with devmode confinement. Default False cohort: an (Optional) string specifying the snap cohort to use revision: an (Optional) string specifying the snap revision to use

Raises: SnapError if some snaps failed to install or were not found.

def remove(snap_names)

Remove specified snap(s) from the system.

Description

Args: snap_names: the name or names of the snaps to install

Raises: SnapError if some snaps failed to install.

def ensure(
    snap_names,
    state: str,
    channel,
    classic,
    devmode: bool,
    cohort,
    revision
)

Ensure specified snaps are in a given state on the system.

Description

Args: snap_names: the name(s) of the snaps to operate on state: a string representation of the desired state, from SnapState channel: an (Optional) channel as a string. Defaults to 'latest' classic: an (Optional) boolean specifying whether it should be added with classic confinement. Default False devmode: an (Optional) boolean specifying whether it should be added with devmode confinement. Default False cohort: an (Optional) string specifying the snap cohort to use revision: an (Optional) integer specifying the snap revision to use

When both channel and revision are specified, the underlying snap install/refresh command will determine the precedence (revision at the time of adding this)

Raises: SnapError if the snap is not in the cache.

def install_local(
    filename: str,
    classic,
    devmode,
    dangerous
)

Perform a snap operation.

Description

Args: 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

def hold_refresh(
    days: int,
    forever: bool
)

Set the system-wide snap refresh hold.

Arguments

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.