# API documentation

## Client

class pylxd.client.Client(endpoint=None, version='1.0', cert=None, verify=True, timeout=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.

  containers

    Instance of `Client.Containers`:

  images

    Instance of `Client.Images`.

  operations

    Instance of `Client.Operations`.

  profiles

    Instance of `Client.Profiles`.

  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()
        # /containers/test/
        >>> print api.containers['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(), :param:`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)

    Create a new certificate.

  classmethod get(client, fingerprint)

    Get a certificate by fingerprint.

## Container

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

  An LXD Container.

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

  class FilesManager(client, container)

    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

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

      Push a file to the container.

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

      Parameters:

        - filepath (str) – The path in the container 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 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

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

      Recursively push directory to the container.

      Recursively pushes directory to the containers named by the dst

      Parameters:

        - src (str) – The source path of directory to copy.

        - dst (str) – The destination path in the container 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 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:

        NotADirectoryError if src is not a directory

      Raises:

        LXDAPIException if an error occurs

  classmethod all(client)

    Get all containers.

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

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

    Create a new container config.

    Parameters:

      - client (Client) – client instance

      - config (dict) – The configuration for the new container.

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

      a container if successful

    Return type:

      `Container`

  execute(commands, environment={}, encoding=None, decode=True, stdin_payload=None, stdin_encoding='utf-8', stdout_handler=None, stderr_handler=None)

    Execute a command on the container.

    In pylxd 2.2, this method will be renamed execute and the existing execute method removed.

    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 recived via stdout

      - stderr_handler (Callable[[str], None]) – Callable than receive as first parameter each message recived via stderr

    Raises:

      ValueError – if the ws4py library is not installed.

    Returns:

      A tuple of (exit_code, stdout, stderr)

    Return type:

      _ContainerExecuteResult() namedtuple

  classmethod exists(client, name)

    Determine whether a container exists.

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

    Freeze the container.

  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 Container.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 container by name.

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

    Migrate a container.

    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 container 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 container 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 container (the target of the migration and not the operation if waited on.)

    Return type:

      `requests.Response`

  publish(public=False, wait=False)

    Publish a container as an image.

    The container 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 container.

    If wait=True, an Image is returned.

  raw_interactive_execute(commands, environment=None)

    Execute a command on the container 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

    Returns:

      Two urls to an interactive websocket and a control socket

    Return type:

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

  rename(name, wait=False)

    Rename a container.

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

    Restart the container.

  restore_snapshot(snapshot_name, wait=False)

    Restore a snapshot using its name.

    Attempts to restore a container using a snapshot previously made. The container 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 container.

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

    Stop the container.

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

    Unfreeze the container.

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

  A container 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 container using this snapshot. The container 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`

## 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.

## 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.

## 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.

  property 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://lxd.readthedocs.io/en/latest/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.