Example #1
0
    def __init__(
        self,
        endpoint=None,
        version="1.0",
        cert=None,
        verify=True,
        timeout=None,
        project=None,
    ):
        """Constructs a LXD client

        :param endpoint: (optional): endpoint can be an http endpoint or
            a path to a unix socket.
        :param version: (optional): API version string to use with LXD
        :param cert: (optional): A tuple of (cert, key) to use with
            the http socket for client authentication
        :param verify: (optional): Either a boolean, in which case it controls
            whether we verify the server's TLS certificate, or a string, in
            which case it must be a path to a CA bundle to use.
            Defaults to ``True``.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) <timeouts>` tuple.
        :param project: (optional) Name of the LXD project to interact with.

        """

        self.project = project
        self.cert = cert
        if endpoint is not None:
            if endpoint.startswith("/") and os.path.isfile(endpoint):
                self.api = _APINode(
                    "http+unix://{}".format(parse.quote(endpoint, safe="")),
                    timeout=timeout,
                )
            else:
                # Extra trailing slashes cause LXD to 301
                endpoint = endpoint.rstrip("/")
                if cert is None and (
                    os.path.exists(DEFAULT_CERTS.cert)
                    and os.path.exists(DEFAULT_CERTS.key)
                ):
                    cert = DEFAULT_CERTS
                self.api = _APINode(
                    endpoint, cert=cert, verify=verify, timeout=timeout, project=project
                )
        else:
            if "LXD_DIR" in os.environ:
                path = os.path.join(os.environ.get("LXD_DIR"), "unix.socket")
            elif os.path.exists("/var/snap/lxd/common/lxd/unix.socket"):
                path = "/var/snap/lxd/common/lxd/unix.socket"
            else:
                path = "/var/lib/lxd/unix.socket"
            endpoint = "http+unix://{}".format(parse.quote(path, safe=""))
            self.api = _APINode(endpoint, timeout=timeout, project=project)
        self.api = self.api[version]

        # Verify the connection is valid.
        try:
            response = self.api.get()
            if response.status_code != 200:
                raise exceptions.ClientConnectionFailed()
            self.host_info = response.json()["metadata"]

        except (
            requests.exceptions.ConnectionError,
            requests.exceptions.InvalidURL,
        ) as e:
            raise exceptions.ClientConnectionFailed(str(e))

        if (
            self.project not in (None, "default")
            and "projects" not in self.host_info["api_extensions"]
        ):
            raise exceptions.ClientConnectionFailed(
                "Remote server doesn't handle projects"
            )

        self.cluster = managers.ClusterManager(self)
        self.certificates = managers.CertificateManager(self)
        self.instances = managers.InstanceManager(self)
        self.containers = managers.ContainerManager(self)
        self.virtual_machines = managers.VirtualMachineManager(self)
        self.images = managers.ImageManager(self)
        self.networks = managers.NetworkManager(self)
        self.operations = managers.OperationManager(self)
        self.profiles = managers.ProfileManager(self)
        self.projects = managers.ProjectManager(self)
        self.storage_pools = managers.StoragePoolManager(self)
        self._resource_cache = None
Example #2
0
    def __init__(self,
                 endpoint=None,
                 version='1.0',
                 cert=None,
                 verify=True,
                 timeout=None):
        """Constructs a LXD client

        :param endpoint: (optional): endpoint can be an http endpoint or
            a path to a unix socket.
        :param version: (optional): API version string to use with LXD
        :param cert: (optional): A tuple of (cert, key) to use with
            the http socket for client authentication
        :param verify: (optional): Either a boolean, in which case it controls
            whether we verify the server's TLS certificate, or a string, in
            which case it must be a path to a CA bundle to use.
            Defaults to ``True``.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) <timeouts>` tuple.

        """

        self.cert = cert
        if endpoint is not None:
            if endpoint.startswith('/') and os.path.isfile(endpoint):
                self.api = _APINode('http+unix://{}'.format(
                    parse.quote(endpoint, safe='')),
                                    timeout=timeout)
            else:
                # Extra trailing slashes cause LXD to 301
                endpoint = endpoint.rstrip('/')
                if cert is None and (os.path.exists(DEFAULT_CERTS.cert)
                                     and os.path.exists(DEFAULT_CERTS.key)):
                    cert = DEFAULT_CERTS
                self.api = _APINode(endpoint,
                                    cert=cert,
                                    verify=verify,
                                    timeout=timeout)
        else:
            if 'LXD_DIR' in os.environ:
                path = os.path.join(os.environ.get('LXD_DIR'), 'unix.socket')
            elif os.path.exists('/var/lib/lxd/unix.socket'):
                path = '/var/lib/lxd/unix.socket'
            else:
                path = '/var/snap/lxd/common/lxd/unix.socket'
            endpoint = 'http+unix://{}'.format(parse.quote(path, safe=''))
            self.api = _APINode(endpoint, timeout=timeout)
        self.api = self.api[version]

        # Verify the connection is valid.
        try:
            response = self.api.get()
            if response.status_code != 200:
                raise exceptions.ClientConnectionFailed()
            self.host_info = response.json()['metadata']

        except (requests.exceptions.ConnectionError,
                requests.exceptions.InvalidURL):
            raise exceptions.ClientConnectionFailed()

        self.cluster = managers.ClusterManager(self)
        self.certificates = managers.CertificateManager(self)
        self.containers = managers.ContainerManager(self)
        self.images = managers.ImageManager(self)
        self.networks = managers.NetworkManager(self)
        self.operations = managers.OperationManager(self)
        self.profiles = managers.ProfileManager(self)
        self.storage_pools = managers.StoragePoolManager(self)