libcloud.container.drivers.lxd module

exception libcloud.container.drivers.lxd.LXDAPIException(message='Unknown Error Occurred', response_dict=None, error_type='')[source]

Bases: Exception

Basic exception to be thrown when LXD API returns with some kind of error

class libcloud.container.drivers.lxd.LXDConnection(user_id, key, secure=True, host=None, port=None, url=None, timeout=None, proxy_url=None, backoff=None, retry_delay=None)[source]

Bases: ConnectionUserAndKey

Initialize user_id and key; set secure to an int based on passed value.

add_default_headers(headers)[source]

Add parameters that are necessary for every request If user and password are specified, include a base http auth header

responseCls

alias of LXDResponse

timeout: int | float | None = 60
class libcloud.container.drivers.lxd.LXDContainerDriver(key='', secret='', secure=False, host='localhost', port=8443, key_file=None, cert_file=None, ca_cert=None, certificate_validator=<function check_certificates>)[source]

Bases: ContainerDriver

Driver for LXD REST API of LXC containers https://lxd.readthedocs.io/en/stable-2.0/rest-api/ https://github.com/lxc/lxd/blob/master/doc/rest-api.md

Parameters:
  • key (str) – API key or username to used (required)

  • secret (str) – Secret password to be used (required)

  • secure (bool) – Whether to use HTTPS or HTTP. Note: Some providers only support HTTPS, and it is on by default.

  • host (str) – Override hostname used for connections.

  • port (int) – Override port used for connections.

Returns:

None

attach_volume(container_id, volume_id, pool_id, name, path, ex_timeout=30)[source]

Attach the volume with id volume_id to the container with id container_id

build_operation_websocket_url(uuid, w_secret)[source]
connectionCls

alias of LXDConnection

create_volume(pool_id, definition, **kwargs)[source]

Create a new storage volume on a given storage pool Operation: sync or async (when copying an existing volume) :return: A StorageVolume representing a storage volume

default_architecture = ''
default_ephemeral = False
default_profiles = 'default'
default_time_out = 30
deploy_container(name, image, cluster=None, parameters=None, start=True, ex_architecture='', ex_profiles=None, ex_ephemeral=False, ex_config=None, ex_devices=None, ex_instance_type=None, ex_timeout=30)[source]

Create a new container Authentication: trusted Operation: async

Parameters:

name – The name of the new container.

64 chars max, ASCII, no slash, no colon and no comma :type name: str

Parameters:
  • image (ContainerImage) – The container image to deploy. Currently not used

  • cluster (ContainerCluster) – The cluster to deploy to, None is default

  • parameters – Container Image parameters.

This parameter should represent the the source dictionary expected by the LXD API call. For more information how this parameter should be structured see https://github.com/lxc/lxd/blob/master/doc/rest-api.md :type parameters: str

Parameters:
  • start (bool) – Start the container on deployment. True is the default

  • ex_architecture (str) – string e.g. x86_64

  • ex_profiles (list) – List of profiles

  • ex_ephemeral (bool) – Whether to destroy the container on shutdown

  • ex_config (dict) – Config override e.g. {“limits.cpu”: “2”}

  • ex_devices (dict) – optional list of devices the container should have

  • ex_instance_type – An optional instance type

to use as basis for limits e.g. “c2.micro” :type ex_instance_type: str

Parameters:

ex_timeout (int) – Timeout

Return type:

libcloud.container.base.Container

destroy_container(container, ex_timeout=30)[source]

Destroy a deployed container. Raises and exception

if the container is running

Parameters:
  • container (Container) – The container to destroy

  • ex_timeout – Time to wait for the operation to complete

:type ex_timeout int

Return type:

:class:`libcloud.container.base.Container

ex_create_network(name, **kwargs)[source]

Create a new network with the given name and and the specified configuration

Authentication: trusted Operation: sync

Parameters:

name (str) – The name of the new network

ex_create_storage_pool(definition)[source]

Create a storage_pool from definition.

Implements POST /1.0/storage-pools

The definition parameter defines what the storage pool will be. An example config for the zfs driver is:

{
“config”: {

“size”: “10GB”

}, “driver”: “zfs”, “name”: “pool1”

}

Note that all fields in the definition parameter are strings. Note that size has to be at least 64MB in order to create the pool

For further details on the storage pool types see: https://lxd.readthedocs.io/en/latest/storage/

The function returns the a StoragePool instance, if it is successfully created, otherwise an LXDAPIException is raised.

Parameters:

definition (dict) – the fields to pass to the LXD API endpoint

Returns:

a storage pool if successful,

raises NotFound if not found :rtype: StoragePool

Raises:

LXDAPIExtensionNotAvailable

if the ‘storage’ api extension is missing. :raises: LXDAPIException if the storage pool couldn’t be created.

ex_delete_network(name)[source]

Delete the network with the given name Authentication: trusted Operation: sync

Parameters:

name (str) – The network name to delete

Returns:

True is successfully deleted the network

ex_delete_storage_pool(id)[source]

Delete the storage pool.

Implements DELETE /1.0/storage-pools/<self.name>

Deleting a storage pool may fail if it is being used. See the LXD documentation for further details.

Raises:

LXDAPIException if the storage pool can’t be deleted.

ex_delete_storage_pool_volume(pool_id, type, name)[source]

Delete a storage volume of a given type on a given storage pool

Parameters:

pool_id

:type str

Parameters:

type

:type str

Parameters:

name

:type str

Returns:

ex_execute_cmd_on_container(cont_id, command, **config)[source]

Description: run a remote command Operation: async

Return: Depends on the the configuration

if wait-for-websocket=true and interactive=false returns a LXDContainerExecuteResult with:

uuid=uuid, secret_0=fds[“0”], secret_1=fds[“1”], secret_2=fds[“2”], control=fds[“control”], output={}, result=None

if wait-for-websocket=true and interactive=true returns a LXDContainerExecuteResult with:

uuid=uuid, secret_0=fds[“0”], secret_1=None, secret_2=None, control=fds[“control”], output={}, result=None

if interactive=false and record-output=true returns a LXDContainerExecuteResult with:

uuid=uuid, secret_0=None, secret_1=None, secret_2=None, control=None, output=output, result=result

if none of the above it assumes that the command has been executed and returns LXDContainerExecuteResult with:

uuid=uuid, secret_0=None, secret_1=None, secret_2=None, control=None, output=None, result=result

in all the above uuid is the operation id

Parameters:

cont_id – The container name to run the commands

“:type cont_id: str

Parameters:

command – a list of strings indicating the commands

and their arguments e.g: [“/bin/bash ls -l”] :type command list

Parameters:

config

Dict with extra arguments.

For example:

width: Initial width of the terminal default 80 height: Initial height of the terminal default 25 user: User to run the command as default 1000 group: Group to run the command as default 1000 cwd: Current working directory default /tmp

wait-for-websocket: Whether to wait for a connection before starting the process. Default False

record-output: Whether to store stdout and stderr (only valid with wait-for-websocket=false) (requires API extension container_exec_recording). Default False

interactive: Whether to allocate a pts device instead of PIPEs. Default true

:type config dict

:rtype LXDContainerExecuteResult

ex_freeze_container(container, ex_timeout=30)[source]

Set the given container into a freeze state

Parameters:
  • container (Container) – The container to restart

  • ex_timeout (int) – Time to wait for the operation to complete

Rtype :class:

`libcloud.container.base.Container

ex_get_api_endpoints()[source]

Description: List of supported APIs Authentication: guest Operation: sync Return: list of supported API endpoint URLs

ex_get_image(fingerprint)[source]

Returns a container image from the given image fingerprint

Parameters:

fingerprint (str) – image fingerprint

Return type:

ContainerImage

ex_get_network(name)[source]

Returns the LXD network with the given name. Implements GET /1.0/networks/<name>

Authentication: trusted Operation: sync

Parameters:

name (str) – The name of the network to return

Return type:

LXDNetwork

ex_get_server_configuration()[source]

Description: Server configuration and environment information Authentication: guest, untrusted or trusted Operation: sync Return: Dict representing server state

The returned configuration depends on whether the connection is trusted or not :rtype: :class: .LXDServerInfo

ex_get_storage_pool(id)[source]

Returns information about a storage pool :param id: the name of the storage pool :rtype: :class: StoragePool

ex_get_storage_pool_volume(pool_id, type, name)[source]

Description: information about a storage volume of a given type on a storage pool Introduced: with API extension storage Authentication: trusted Operation: sync Return: A StorageVolume representing a storage volume

ex_get_volume_by_name(name, vol_type='custom')[source]

Returns a storage volume that has the given name. The function will loop over all storage-polls available and will pick the first volume from the first storage poll that matches the given name. Thus this function can be quite expensive

Parameters:
  • name (str) – The name of the volume to look for

  • vol_type (str) – The type of the volume default is custom

Returns:

A StorageVolume representing a storage volume

ex_has_image(alias)[source]

Helper function. Returns true and the image fingerprint if the image with the given alias exists on the host.

Parameters:

alias (str) – the image alias

Return type:

tupple :: (boolean, str)

ex_list_networks()[source]

Returns a list of networks. Implements GET /1.0/networks Authentication: trusted Operation: sync

Return type:

list of LXDNetwork objects

ex_list_storage_pool_volumes(pool_id, detailed=True)[source]

Description: list of storage volumes associated with the given storage pool

Parameters:
  • pool_id – the id of the storage pool to query

  • detailed – boolean flag.

If True extra API calls are made to fill in the missing details

of the storage volumes

Authentication: trusted Operation: sync Return: list of storage volumes that currently exist on a given storage pool

Return type:

A list of :class: StorageVolume

ex_list_storage_pools(detailed=True)[source]

Returns a list of storage pools defined currently defined on the host

Description: list of storage pools Authentication: trusted Operation: sync

“:rtype: list of StoragePool items

ex_replace_storage_volume_config(pool_id, type, name, definition)[source]

Replace the storage volume information :param pool_id: :param type: :param name: :param definition

ex_unfreeze_container(container, ex_timeout=30)[source]

Set the given container into unfreeze state

Parameters:
  • container (Container) – The container to restart

  • ex_timeout (int) – Time to wait for the operation to complete

Rtype :class:

`libcloud.container.base.Container

get_container(id, ex_get_ip_addr=True)[source]

Get a container by ID

Parameters:
  • id (str) – The ID of the container to get

  • ex_get_ip_addr – Indicates whether ip addresses

should also be included. This requires an extra GET request :type ex_get_ip_addr: boolean`

Return type:

libcloud.container.base.Container

install_image(path, ex_timeout=30, **ex_img_data)[source]

Install a container image from a remote path. Not that the path currently is not used. Image data should be provided under the key ‘ex_img_data’. Creating an image in LXD is an asynchronous operation

Parameters:
  • path (str) – Path to the container image

  • ex_timeout (int) – Time to wait before signaling timeout

  • ex_img_data (dict) – Dictionary describing the image data

Return type:

ContainerImage

list_containers(image=None, cluster=None, ex_detailed=True)[source]

List the deployed container images

Parameters:
  • image (ContainerImage) – Filter to containers with a certain image

  • cluster (ContainerCluster) – Filter to containers in a cluster

  • ex_detailed – Flag indicating whether detail info

of the containers is required. This will cause a GET request for every container present in the host. Default is True :type ex_detailed: bool

Return type:

list of :class:`libcloud.container.base.Container

list_images()[source]

List of URLs for images the server is publishing

Return type:

list of ContainerImage

name = 'LXD'
restart_container(container, ex_timeout=30, ex_force=True, ex_stateful=True)[source]

Restart a deployed container

Parameters:
  • container (Container) – The container to restart

  • ex_timeout (int) – Time to wait for the operation to complete

  • ex_force (boolean) –

  • ex_stateful (boolean) –

Return type:

:class:`libcloud.container.base.Container

start_container(container, ex_timeout=30, ex_force=True, ex_stateful=True)[source]

Start a container

Parameters:
  • container (libcloud.container.base.Container) – The container to start

  • ex_timeout (int) – Time to wait for the operation to complete

  • ex_force (boolean) –

  • ex_stateful (boolean) –

Return type:

libcloud.container.base.Container

stop_container(container, ex_timeout=30, ex_force=True, ex_stateful=True)[source]

Stop the given container

Parameters:
  • container (libcloud.container.base.Container) – The container to be stopped

  • ex_timeout (int) – Time to wait for the operation to complete

  • ex_force (boolean) –

  • ex_stateful (boolean) –

Return type:

:class:`libcloud.container.base.Container

supports_clusters = False

Whether the driver supports containers being deployed into clusters

type = 'lxd'
version = '1.0'
website = 'https://linuxcontainers.org/'
class libcloud.container.drivers.lxd.LXDContainerExecuteResult(uuid, secret_0, secret_1, secret_2, control, output, result)

Bases: tuple

Create new instance of LXDContainerExecuteResult(uuid, secret_0, secret_1, secret_2, control, output, result)

control

Alias for field number 4

output

Alias for field number 5

result

Alias for field number 6

secret_0

Alias for field number 1

secret_1

Alias for field number 2

secret_2

Alias for field number 3

uuid

Alias for field number 0

class libcloud.container.drivers.lxd.LXDNetwork[source]

Bases: object

Utility class representing an LXD network

classmethod build_from_response(metadata)[source]
class libcloud.container.drivers.lxd.LXDResponse(response, connection)[source]

Bases: JsonResponse

Parameters:
  • response (httplib.HTTPResponse) – HTTP response object. (optional)

  • connection (Connection) – Parent connection object.

parse_body()[source]

Parse response body.

Override in a provider’s subclass.

Returns:

Parsed body.

Return type:

str

parse_error()[source]

Parse the error messages.

Override in a provider’s subclass.

Returns:

Parsed error.

Return type:

str

success()[source]

Determine if our request was successful.

The meaning of this can be arbitrary; did we receive OK status? Did the node get created? Were we authenticated?

Return type:

bool

Returns:

True or False

valid_response_codes = [<HTTPStatus.OK: 200>, <HTTPStatus.ACCEPTED: 202>, <HTTPStatus.CREATED: 201>, <HTTPStatus.NO_CONTENT: 204>]
class libcloud.container.drivers.lxd.LXDServerInfo[source]

Bases: object

Wraps the response form /1.0

classmethod build_from_response(metadata)[source]
class libcloud.container.drivers.lxd.LXDStoragePool(name, driver, used_by, config, managed)[source]

Bases: object

Utility class representing an LXD storage pool https://lxd.readthedocs.io/en/latest/storage/

class libcloud.container.drivers.lxd.LXDtlsConnection(key, secret, secure=True, host='localhost', port=8443, ca_cert='', key_file=None, cert_file=None, certificate_validator=None, **kwargs)[source]

Bases: KeyCertificateConnection

Initialize cert_file; set secure to an int based on passed value.

add_default_headers(headers)[source]

Adds default headers (such as Authorization, X-Foo-Bar) to the passed headers

Should return a dictionary.

responseCls

alias of LXDResponse

libcloud.container.drivers.lxd.assert_response(response_dict, status_code)[source]

Basic checks that the response is of the type the client is expecting

libcloud.container.drivers.lxd.check_certificates(key_file, cert_file, **kwargs)[source]

Basic checks for the provided certificates in LXDtlsConnection

libcloud.container.drivers.lxd.strip_http_prefix(host)[source]