API documentation

Client

class pylxd.client.Client(endpoint=None, version='1.0', cert=None, verify=True, timeout=None, project=None)

Client class for LXD REST API.

This client wraps all the functionality required to interact with LXD, and is meant to be the sole entry point.

instances

A models.Instance.

containers

A models.Container.

virtual_machines

A models.VirtualMachine.

images

A models.Image.

operations

A models.Operation.

profiles

A models.Profile.

projects

A models.Project.

api

This attribute provides tree traversal syntax to LXD’s REST API for lower-level interaction.

Use the name of the url part as attribute or item of an api object to create another api object appended with the new url part name, ie:

>>> api = Client().api
# /
>>> response = api.get()
# Check status code and response
>>> print response.status_code, response.json()
# /instances/test/
>>> print api.instances['test'].get().json()
assert_has_api_extension(name)

Asserts that the name api_extension exists. If not, then is raises the LXDAPIExtensionNotAvailable error.

Parameters:name (str) – the api_extension to test for
Returns:None
Raises:pylxd.exceptions.LXDAPIExtensionNotAvailable
events(websocket_client=None, event_types=None)

Get a websocket client for getting events.

/events is a websocket url, and so must be handled differently than most other LXD API endpoints. This method returns a client that can be interacted with like any regular python socket.

An optional websocket_client parameter can be specified for implementation-specific handling of events as they occur.

Parameters:
  • websocket_client (ws4py.client import WebSocketBaseClient) – Optional websocket client can be specified for implementation-specific handling of events as they occur.
  • event_types (Set[EventType]) – Optional set of event types to propagate. Omit this argument or specify {EventTypes.All} to receive all events.
Returns:

instance of the websocket client

Return type:

Option[_WebsocketClient(), websocket_client]

has_api_extension(name)

Return True if the name api extension exists.

Parameters:name (str) – the api_extension to look for.
Returns:True if extension exists
Return type:bool

Exceptions

class pylxd.exceptions.LXDAPIException(response)

A generic exception for representing unexpected LXD API responses.

LXD API responses are clearly documented, and are either a standard return value, and background operation, or an error. This exception is raised on an error case, or when the response status code is not expected for the response.

This exception should only be raised in cases where the LXD REST API has returned something unexpected.

class pylxd.exceptions.NotFound(response)

An exception raised when an object is not found.

class pylxd.exceptions.ClientConnectionFailed

An exception raised when the Client connection fails.

Certificate

class pylxd.models.Certificate(client, **kwargs)

A LXD certificate.

classmethod all(client)

Get all certificates.

classmethod create(client, password, cert_data, cert_type='client', name='', projects=None, restricted=False)

Create a new certificate.

classmethod get(client, fingerprint)

Get a certificate by fingerprint.

Container

class pylxd.models.Instance(*args, **kwargs)

An LXD Instance.

This class is not intended to be used directly, but rather to be used via Client.instance.create.

class FilesManager(instance)

A pseudo-manager for namespacing file operations.

delete_available()

File deletion is an extension API and may not be available. https://github.com/lxc/lxd/blob/master/doc/api-extensions.md#file_delete

mk_dir(path, mode=None, uid=None, gid=None)

Creates an empty directory on the container. This pushes an empty directory to the containers file system named by the filepath.

Parameters:
  • path (str) – The path in the container to to store the data in.
  • mode (Union[oct, int, str]) – The unit mode to store the file with. The default of None stores the file with the current mask of 0700, which is the lxd default.
  • uid (int) – The uid to use inside the container. Default of None results in 0 (root).
  • gid (int) – The gid to use inside the container. Default of None results in 0 (root).
Raises:

LXDAPIException if something goes wrong

put(filepath, data, mode=None, uid=None, gid=None)

Push a file to the instance.

This pushes a single file to the instances file system named by the filepath.

Parameters:
  • filepath (str) – The path in the instance to to store the data in.
  • data (bytes or str) – The data to store in the file.
  • mode (Union[oct, int, str]) – The unit mode to store the file with. The default of None stores the file with the current mask of 0700, which is the lxd default.
  • uid (int) – The uid to use inside the instance. Default of None results in 0 (root).
  • gid (int) – The gid to use inside the instance. Default of None results in 0 (root).
Raises:

LXDAPIException if something goes wrong

recursive_get(remote_path, local_path)

Recursively pulls a directory from the container. Pulls the directory named remote_path from the container and creates a local folder named local_path with the content of remote_path. If remote_path is a file, it will be copied to local_path.

Parameters:
  • remote_path (str) – The directory path on the container.
  • local_path (str) – The path at which the directory will be stored.
Raises:

LXDAPIException if an error occurs

recursive_put(src, dst, mode=None, uid=None, gid=None)

Recursively push directory to the instance.

Recursively pushes directory to the instances named by the dst

Parameters:
  • src (str) – The source path of directory to copy.
  • dst (str) – The destination path in the instance of directory to copy
  • mode (Union[oct, int, str]) – The unit mode to store the file with. The default of None stores the file with the current mask of 0700, which is the lxd default.
  • uid (int) – The uid to use inside the instance. Default of None results in 0 (root).
  • gid (int) – The gid to use inside the instance. Default of None results in 0 (root).
Raises:

NotADirectoryError if src is not a directory

Raises:

LXDAPIException if an error occurs

classmethod all(client)

Get all instances.

Instances returned from this method will only have the name set, as that is the only property returned from LXD. If more information is needed, Instance.sync is the method call that should be used.

classmethod create(client, config, wait=False, target=None)

Create a new instance config.

Parameters:
  • client (Client) – client instance
  • config (dict) – The configuration for the new instance.
  • wait (bool) – Whether to wait for async operations to complete.
  • target (str) – If in cluster mode, the target member.
Raises:

LXDAPIException – if something goes wrong.

Returns:

an instance if successful

Return type:

Instance

execute(commands, environment=None, encoding=None, decode=True, stdin_payload=None, stdin_encoding='utf-8', stdout_handler=None, stderr_handler=None, user=None, group=None, cwd=None)

Execute a command on the instance. stdout and stderr are buffered if no handler is given.

Parameters:
  • commands ([str]) – The command and arguments as a list of strings
  • environment ({str: str}) – The environment variables to pass with the command
  • encoding (str) – The encoding to use for stdout/stderr if the param decode is True. If encoding is None, then no override is performed and whatever the existing encoding from LXD is used.
  • decode (bool) – Whether to decode the stdout/stderr or just return the raw buffers.
  • stdin_payload (Can be a file, string, bytearray, generator or ws4py Message object) – Payload to pass via stdin
  • stdin_encoding – Encoding to pass text to stdin (default utf-8)
  • stdout_handler (Callable[[str], None]) – Callable than receive as first parameter each message received via stdout
  • stderr_handler (Callable[[str], None]) – Callable than receive as first parameter each message received via stderr
  • user (int) – User to run the command as
  • group (int) – Group to run the command as
  • cwd (str) – Current working directory
Returns:

A tuple of (exit_code, stdout, stderr)

Return type:

_InstanceExecuteResult() namedtuple

classmethod exists(client, name)

Determine whether a instance exists.

freeze(timeout=30, force=True, wait=False)

Freeze the instance.

generate_migration_data(live=False)

Generate the migration data.

This method can be used to handle migrations where the client connection uses the local unix socket. For more information on migration, see Instance.migrate.

Parameters:live (bool) – Whether to include “live”: “true” in the migration
Raises:LXDAPIException if the request to migrate fails
Returns:dictionary of migration data suitable to send to an new client to complete a migration.
Return type:Dict[str, ANY]
classmethod get(client, name)

Get a instance by name.

migrate(new_client, live=False, wait=False)

Migrate a instance.

Destination host information is contained in the client connection passed in.

If the live param is True, then a live migration is attempted, otherwise a non live one is running.

If the instance is running for live migration, it either must be shut down first or criu must be installed on the source and destination machines and the live param should be True.

Parameters:
  • new_client (pylxd.client.Client) – the pylxd client connection to migrate the instance to.
  • live (bool) – whether to perform a live migration
  • wait (bool) – if True, wait for the migration to complete
Raises:

LXDAPIException if any of the API calls fail.

Raises:

ValueError if source of target are local connections

Returns:

the response from LXD of the new instance (the target of the migration and not the operation if waited on.)

Return type:

requests.Response

publish(public=False, wait=False)

Publish a instance as an image.

The instance must be stopped in order publish it as an image. This method does not enforce that constraint, so a LXDAPIException may be raised if this method is called on a running instance.

If wait=True, an Image is returned.

raw_interactive_execute(commands, environment=None, user=None, group=None, cwd=None)

Execute a command on the instance interactively and returns urls to websockets. The urls contain a secret uuid, and can be accesses without further authentication. The caller has to open and manage the websockets themselves.

Parameters:
  • commands ([str]) – The command and arguments as a list of strings (most likely a shell)
  • environment ({str: str}) – The environment variables to pass with the command
  • user (int) – User to run the command as
  • group (int) – Group to run the command as
  • cwd (str) – Current working directory
Returns:

Two urls to an interactive websocket and a control socket

Return type:

{‘ws’:str,’control’:str}

rename(name, wait=False)

Rename an instance.

restart(timeout=30, force=True, wait=False)

Restart the instance.

restore_snapshot(snapshot_name, wait=False)

Restore a snapshot using its name.

Attempts to restore a instance using a snapshot previously made. The instance should be stopped, but the method does not enforce this constraint, so an LXDAPIException may be raised if this method fails.

Parameters:
  • snapshot_name (str) – the name of the snapshot to restore from
  • wait (boolean) – wait until the operation is completed.
Raises:

LXDAPIException if the the operation fails.

Returns:

the original response from the restore operation (not the operation result)

Return type:

requests.Response

start(timeout=30, force=True, wait=False)

Start the instance.

stop(timeout=30, force=True, wait=False)

Stop the instance.

unfreeze(timeout=30, force=True, wait=False)

Unfreeze the instance.

class pylxd.models.Container(*args, **kwargs)

Flavour of models.Instance for containers.

class pylxd.models.Snapshot(client, **kwargs)

A instance snapshot.

publish(public=False, wait=False)

Publish a snapshot as an image.

If wait=True, an Image is returned.

This functionality is currently broken in LXD. Please see https://github.com/lxc/lxd/issues/2201 - The implementation here is mostly a guess. Once that bug is fixed, we can verify that this works, or file a bug to fix it appropriately.

rename(new_name, wait=False)

Rename a snapshot.

restore(wait=False)

Restore this snapshot.

Attempts to restore a instance using this snapshot. The instance should be stopped, but the method does not enforce this constraint, so an LXDAPIException may be raised if this method fails.

Parameters:wait (boolean) – wait until the operation is completed.
Raises:LXDAPIException if the the operation fails.
Returns:the original response from the restore operation (not the operation result)
Return type:requests.Response

Virtual Machine

class pylxd.models.VirtualMachine(*args, **kwargs)

Flavour of models.Instance for VMs.

Image

class pylxd.models.Image(client, **kwargs)

A LXD Image.

add_alias(name, description)

Add an alias to the image.

classmethod all(client)

Get all images.

copy(new_client, public=None, auto_update=None, wait=False)

Copy an image to a another LXD.

Destination host information is contained in the client connection passed in.

classmethod create(client, image_data, metadata=None, public=False, wait=True)

Create an image.

If metadata is provided, a multipart form data request is formed to push metadata and image together in a single request. The metadata must be a tar achive.

wait parameter is now ignored, as the image fingerprint cannot be reliably determined consistently until after the image is indexed.

classmethod create_from_simplestreams(client, server, alias, public=False, auto_update=False)

Copy an image from simplestreams.

classmethod create_from_url(client, url, public=False, auto_update=False)

Copy an image from an url.

delete_alias(name)

Delete an alias from the image.

classmethod exists(client, fingerprint, alias=False)

Determine whether an image exists.

If alias is True, look up the image by its alias, rather than its fingerprint.

export()

Export the image.

Because the image itself may be quite large, we stream the download in 1kb chunks, and write it to a temporary file on disk. Once that file is closed, it is deleted from the disk.

classmethod get(client, fingerprint)

Get an image.

classmethod get_by_alias(client, alias)

Get an image by its alias.

Network

class pylxd.models.Network(client, **kwargs)

Model representing a LXD network.

classmethod all(client)

Get all networks.

Parameters:client (Client) – client instance
Return type:list[Network]
classmethod create(client, name, description=None, type=None, config=None)

Create a network.

Parameters:
  • client (Client) – client instance
  • name (str) – name of the network
  • description (str) – description of the network
  • type (str) – type of the network
  • config (dict) – additional configuration
classmethod exists(client, name)

Determine whether network with provided name exists.

Parameters:
  • client (Client) – client instance
  • name (str) – name of the network
Returns:

True if network exists, False otherwise

Return type:

bool

classmethod get(client, name)

Get a network by name.

Parameters:
  • client (Client) – client instance
  • name (str) – name of the network
Returns:

network instance (if exists)

Return type:

Network

Raises:

NotFound if network does not exist

rename(new_name)

Rename a network.

Parameters:new_name (str) – new name of the network
Returns:Renamed network instance
Return type:Network
save(*args, **kwargs)

Save data to the server.

This method should write the new data to the server via marshalling. It should be a no-op when the object is not dirty, to prevent needless I/O.

state()

Get network state.

Operation

class pylxd.models.Operation(**kwargs)

An LXD operation.

If the LXD server sends attributes that this version of pylxd is unaware of then a warning is printed. By default the warning is issued ONCE and then supressed for every subsequent attempted setting. The warnings can be completely suppressed by setting the environment variable PYLXD_WARNINGS to ‘none’, or always displayed by setting the PYLXD_WARNINGS variable to ‘always’.

classmethod get(client, operation_id)

Get an operation.

wait()

Wait for the operation to complete and return.

classmethod wait_for_operation(client, operation_id)

Get an operation and wait for it to complete.

Profile

class pylxd.models.Profile(client, **kwargs)

A LXD profile.

classmethod all(client)

Get all profiles.

classmethod create(client, name, config=None, devices=None)

Create a profile.

classmethod exists(client, name)

Determine whether a profile exists.

classmethod get(client, name)

Get a profile.

rename(new_name)

Rename the profile.

Project

class pylxd.models.Project(client, **kwargs)

A LXD project.

This corresponds to the LXD endpoint at /1.0/projects.

api_extension: ‘projects’

classmethod all(client)

Get all projects.

classmethod create(client, name, description=None, config=None)

Create a project.

classmethod exists(client, name)

Determine whether a project exists.

classmethod get(client, name)

Get a project.

rename(new_name)

Rename the project.

Storage Pool

class pylxd.models.StoragePool(*args, **kwargs)

An LXD storage_pool.

This corresponds to the LXD endpoint at /1.0/storage-pools

api_extension: ‘storage’

classmethod all(client)

Get all storage_pools.

Implements GET /1.0/storage-pools

Note that the returned list is ‘sparse’ in that only the name of the pool is populated. If any of the attributes are used, then the sync function is called to populate the object fully.

Parameters:client (pylxd.client.Client) – The pylxd client object
Returns:a storage pool if successful, raises NotFound if not found
Return type:[pylxd.models.storage_pool.StoragePool]
Raises:pylxd.exceptions.LXDAPIExtensionNotAvailable if the ‘storage’ api extension is missing.
api

Provides an object with the endpoint:

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

Used internally to construct endpoints.

Returns:an API node with the named endpoint
Return type:pylxd.client._APINode
classmethod create(client, definition)

Create a storage_pool from config.

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.

For further details on the storage pool types see: https://linuxcontainers.org/lxd/docs/master/storage/

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

Parameters:
  • client (pylxd.client.Client) – The pylxd client object
  • definition (dict) – the fields to pass to the LXD API endpoint
Returns:

a storage pool if successful, raises NotFound if not found

Return type:

pylxd.models.storage_pool.StoragePool

Raises:

pylxd.exceptions.LXDAPIExtensionNotAvailable if the ‘storage’ api extension is missing.

Raises:

pylxd.exceptions.LXDAPIException if the storage pool couldn’t be created.

delete()

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:pylxd.exceptions.LXDAPIException if the storage pool can’t be deleted.
classmethod exists(client, name)

Determine whether a storage pool exists.

A convenience method to determine a pool exists. However, it is better to try to fetch it and catch the pylxd.exceptions.NotFound exception, as otherwise the calling code is like to fetch the pool twice. Only use this if the calling code doesn’t need the actual storage pool information.

Parameters:
  • client (pylxd.client.Client) – The pylxd client object
  • name (str) – the name of the storage pool to get
Returns:

True if the storage pool exists, False if it doesn’t.

Return type:

bool

Raises:

pylxd.exceptions.LXDAPIExtensionNotAvailable if the ‘storage’ api extension is missing.

classmethod get(client, name)

Get a storage_pool by name.

Implements GET /1.0/storage-pools/<name>

Parameters:
  • client (pylxd.client.Client) – The pylxd client object
  • name (str) – the name of the storage pool to get
Returns:

a storage pool if successful, raises NotFound if not found

Return type:

pylxd.models.storage_pool.StoragePool

Raises:

pylxd.exceptions.NotFound

Raises:

pylxd.exceptions.LXDAPIExtensionNotAvailable if the ‘storage’ api extension is missing.

patch(patch_object, wait=False)

Patch the storage pool.

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

Patching the object allows for more fine grained changes to the config. The object is refreshed if the PATCH is successful. If this is not required, then use the client api directly.

Parameters:
  • patch_object (dict) – A dictionary. The most useful key will be the config key.
  • wait (bool) – Whether to wait for async operations to complete.
Raises:

pylxd.exceptions.LXDAPIException if the storage pool can’t be modified.

put(put_object, wait=False)

Put the storage pool.

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

Putting to a storage pool may fail if the new configuration is incompatible with the pool. See the LXD documentation for further details.

Note that the object is refreshed with a sync if the PUT is successful. If this is not desired, then the raw API on the client should be used.

Parameters:
  • put_object (dict) – A dictionary. The most useful key will be the config key.
  • wait (bool) – Whether to wait for async operations to complete.
Raises:

pylxd.exceptions.LXDAPIException if the storage pool can’t be modified.

save(wait=False)

Save the model using PUT back to the LXD server.

Implements PUT /1.0/storage-pools/<self.name> automagically

The fields affected are: description and config. Note that they are replaced in their entirety. If finer grained control is required, please use the patch() method directly.

Updating a storage pool may fail if the config is not acceptable to LXD. An LXDAPIException will be generated in that case.

Raises:pylxd.exceptions.LXDAPIException if the storage pool can’t be deleted.

Cluster

class pylxd.models.Cluster(*args, **kwargs)

An LXD Cluster.

classmethod get(client, *args)

Get cluster details

class pylxd.models.ClusterMember(client, **kwargs)

A LXD cluster member.

classmethod all(client, *args)

Get all cluster members.

classmethod get(client, server_name)

Get a cluster member by name.