Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_lxd.py

raw
1 # Copyright (c) 2016, Hiroaki Nakamura <[email protected]>
2 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
3 # SPDX-License-Identifier: BSD-2-Clause
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import http.client as http_client
11 import json
12 import os
13 import socket
14 import ssl
15 import typing as t
16 from urllib.parse import urlparse
17
18 from ansible.module_utils.urls import generic_urlparse
19
20 # httplib/http.client connection using unix domain socket
21 HTTPConnection = http_client.HTTPConnection
22 HTTPSConnection = http_client.HTTPSConnection
23
24
25 class UnixHTTPConnection(HTTPConnection):
26 def __init__(self, path: str) -> None:
27 HTTPConnection.__init__(self, "localhost")
28 self.path = path
29
30 def connect(self):
31 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
32 sock.connect(self.path)
33 self.sock = sock
34
35
36 class LXDClientException(Exception):
37 def __init__(self, msg: str, **kwargs) -> None:
38 self.msg = msg
39 self.kwargs = kwargs
40
41
42 class LXDClient:
43 def __init__(
44 self,
45 url: str,
46 key_file: str | None = None,
47 cert_file: str | None = None,
48 debug: bool = False,
49 server_cert_file: str | None = None,
50 server_check_hostname: bool = True,
51 ) -> None:
52 """LXD Client.
53
54 :param url: The URL of the LXD server. (e.g. unix:/var/lib/lxd/unix.socket or https://127.0.0.1)
55 :param key_file: The path of the client certificate key file.
56 :param cert_file: The path of the client certificate file.
57 :param debug: The debug flag. The request and response are stored in logs when debug is true.
58 :param server_cert_file: The path of the server certificate file.
59 :param server_check_hostname: Whether to check the server's hostname as part of TLS verification.
60 """
61 self.url = url
62 self.debug = debug
63 self.logs: list[dict[str, t.Any]] = []
64 self.connection: UnixHTTPConnection | HTTPSConnection
65 if url.startswith("https:"):
66 self.cert_file = cert_file
67 self.key_file = key_file
68 parts = generic_urlparse(urlparse(self.url))
69 ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
70 if server_cert_file:
71 # Check that the received cert is signed by the provided server_cert_file
72 ctx.load_verify_locations(cafile=server_cert_file)
73 ctx.check_hostname = server_check_hostname
74 ctx.load_cert_chain(cert_file, keyfile=key_file) # type: ignore # TODO!
75 self.connection = HTTPSConnection(parts.get("netloc"), context=ctx)
76 elif url.startswith("unix:"):
77 unix_socket_path = url[len("unix:") :]
78 self.connection = UnixHTTPConnection(unix_socket_path)
79 else:
80 raise LXDClientException("URL scheme must be unix: or https:")
81
82 def do(self, method: str, url: str, body_json=None, ok_error_codes=None, timeout=None, wait_for_container=None):
83 resp_json = self._send_request(method, url, body_json=body_json, ok_error_codes=ok_error_codes, timeout=timeout)
84 if resp_json["type"] == "async":
85 url = f"{resp_json['operation']}/wait"
86 resp_json = self._send_request("GET", url)
87 if wait_for_container:
88 while resp_json["metadata"]["status"] == "Running":
89 resp_json = self._send_request("GET", url)
90 if resp_json["metadata"]["status"] != "Success":
91 self._raise_err_from_json(resp_json)
92 return resp_json
93
94 def authenticate(self, trust_password):
95 body_json = {"type": "client", "password": trust_password}
96 return self._send_request("POST", "/1.0/certificates", body_json=body_json)
97
98 def _send_request(self, method: str, url: str, body_json=None, ok_error_codes=None, timeout=None):
99 try:
100 body = json.dumps(body_json)
101 self.connection.request(method, url, body=body)
102 resp = self.connection.getresponse()
103 resp_data = resp.read()
104 resp_json = json.loads(resp_data)
105 self.logs.append(
106 {
107 "type": "sent request",
108 "request": {"method": method, "url": url, "json": body_json, "timeout": timeout},
109 "response": {"json": resp_json},
110 }
111 )
112 resp_type = resp_json.get("type", None)
113 if resp_type == "error":
114 if ok_error_codes is not None and resp_json["error_code"] in ok_error_codes:
115 return resp_json
116 if resp_json["error"] == "Certificate already in trust store":
117 return resp_json
118 self._raise_err_from_json(resp_json)
119 return resp_json
120 except OSError as e:
121 raise LXDClientException("cannot connect to the LXD server", err=e) from e
122
123 def _raise_err_from_json(self, resp_json):
124 err_params = {}
125 if self.debug:
126 err_params["logs"] = self.logs
127 raise LXDClientException(self._get_err_from_resp_json(resp_json), **err_params)
128
129 @staticmethod
130 def _get_err_from_resp_json(resp_json):
131 err = None
132 metadata = resp_json.get("metadata", None)
133 if metadata is not None:
134 err = metadata.get("err", None)
135 if err is None:
136 err = resp_json.get("error", None)
137 return err
138
139
140 def default_key_file() -> str:
141 return os.path.expanduser("~/.config/lxc/client.key")
142
143
144 def default_cert_file() -> str:
145 return os.path.expanduser("~/.config/lxc/client.crt")