qodalis-cli-server-plugin-docker 1.0.0b39__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,482 @@
1
+ """A small client of the Docker Engine API over plain HTTP/1.1 on asyncio streams: unix sockets, TCP and TLS.
2
+
3
+ It speaks the unversioned paths (the engine uses its own latest API), buffers answers under one timeout, streams the long
4
+ ones (logs, pulls, events) and hijacks the connection for an exec (``Connection: Upgrade``). Each request opens its own
5
+ connection (``Connection: close``), so nothing is bound to an event loop and a stuck engine cannot hold a pool."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import json
11
+ import socket
12
+ import os
13
+ import ssl
14
+ from dataclasses import dataclass
15
+ from typing import Any, AsyncIterator, Mapping, Optional
16
+ from urllib.parse import quote, urlsplit
17
+
18
+
19
+ class DockerError(Exception):
20
+ """An error with the HTTP status a route answers with."""
21
+
22
+ def __init__(self, status: int, message: str) -> None:
23
+ super().__init__(message)
24
+ self.status = status
25
+ self.message = message
26
+
27
+
28
+ @dataclass
29
+ class DockerHostConfig:
30
+ """A host's connection settings (the default host's ``endpoint``/``tls*`` settings, or an entry of ``hosts``)."""
31
+
32
+ endpoint: str
33
+ tls_ca: Optional[str] = None
34
+ tls_cert: Optional[str] = None
35
+ tls_key: Optional[str] = None
36
+ tls_verify: bool = True
37
+
38
+ def key(self) -> tuple[Any, ...]:
39
+ return (self.endpoint, self.tls_ca, self.tls_cert, self.tls_key, self.tls_verify)
40
+
41
+
42
+ @dataclass
43
+ class ParsedEndpoint:
44
+ """An endpoint split into how to connect."""
45
+
46
+ #: The socket path of a ``unix://`` endpoint.
47
+ socket_path: Optional[str] = None
48
+ host: Optional[str] = None
49
+ port: Optional[int] = None
50
+ #: ``https`` when TLS is on.
51
+ protocol: str = "http"
52
+ #: The endpoint as shown: no credentials, no paths of keys.
53
+ display: str = ""
54
+
55
+
56
+ def parse_endpoint(config: DockerHostConfig) -> ParsedEndpoint:
57
+ """Parses ``unix:///var/run/docker.sock``, ``tcp://host:2375``, ``http(s)://host:port`` or a bare socket path."""
58
+ raw = str(config.endpoint or "").strip()
59
+ if not raw:
60
+ raise ValueError("the endpoint is empty")
61
+ if raw.startswith("/"):
62
+ return ParsedEndpoint(socket_path=raw, display=f"unix://{raw}")
63
+ if raw.startswith("unix://"):
64
+ path = raw[len("unix://"):]
65
+ if not path.startswith("/"):
66
+ raise ValueError(f"invalid unix endpoint: {raw}")
67
+ return ParsedEndpoint(socket_path=path, display=f"unix://{path}")
68
+ try:
69
+ url = urlsplit(raw)
70
+ port_value = url.port
71
+ except ValueError as exc:
72
+ raise ValueError(f"invalid endpoint: {raw}") from exc
73
+ if not url.scheme or "://" not in raw:
74
+ raise ValueError(f"invalid endpoint: {raw}")
75
+ if url.scheme not in ("tcp", "http", "https"):
76
+ raise ValueError(f"unsupported endpoint scheme: {url.scheme}")
77
+ if not url.hostname:
78
+ raise ValueError(f"invalid endpoint: {raw}")
79
+ default_port = 2376 if url.scheme == "https" else 2375
80
+ port = port_value if port_value is not None else default_port
81
+ tls = url.scheme == "https" or bool(config.tls_cert) or bool(config.tls_ca) or port == 2376
82
+ hostname = f"[{url.hostname}]" if ":" in url.hostname else url.hostname
83
+ return ParsedEndpoint(host=url.hostname, port=port, protocol="https" if tls else "http", display=f"{url.scheme}://{hostname}:{port}")
84
+
85
+
86
+ def query_string(query: Optional[Mapping[str, Any]]) -> str:
87
+ if not query:
88
+ return ""
89
+ parts = []
90
+ for key, value in query.items():
91
+ if value is None:
92
+ continue
93
+ if isinstance(value, bool):
94
+ value = 1 if value else 0
95
+ elif isinstance(value, float) and value.is_integer():
96
+ value = int(value)
97
+ parts.append(f"{quote(str(key), safe=_SAFE)}={quote(str(value), safe=_SAFE)}")
98
+ return f"?{'&'.join(parts)}" if parts else ""
99
+
100
+
101
+ #: What ``encodeURIComponent`` leaves alone.
102
+ _SAFE = "-_.!~*'()"
103
+
104
+
105
+ def encode_component(value: str) -> str:
106
+ """``encodeURIComponent``. Callers refuse ``.`` and ``..`` first (:func:`assert_path_name`)."""
107
+ return quote(value, safe=_SAFE)
108
+
109
+
110
+ def assert_path_name(kind: str, name: Optional[str]) -> None:
111
+ """A name or id of ``.`` or ``..`` would be normalised away from the engine path (``/volumes/..`` is ``/``): never sent."""
112
+ if name in (".", ".."):
113
+ raise DockerError(404, f"no such {kind}: {name}")
114
+
115
+
116
+ def network_message(err: BaseException) -> str:
117
+ """The text of a connection failure (the part after ``cannot reach Docker at <host>:``)."""
118
+ if isinstance(err, (asyncio.TimeoutError, TimeoutError)):
119
+ return "timed out"
120
+ if isinstance(err, ConnectionRefusedError):
121
+ return "connection refused"
122
+ if isinstance(err, FileNotFoundError):
123
+ return "the socket does not exist"
124
+ if isinstance(err, PermissionError):
125
+ return "permission denied"
126
+ if isinstance(err, socket.gaierror):
127
+ return "host not found"
128
+ return str(err) or type(err).__name__
129
+
130
+
131
+ @dataclass
132
+ class EngineResponse:
133
+ status: int
134
+ headers: dict[str, str]
135
+ body: bytes
136
+
137
+
138
+ class _Head:
139
+ def __init__(self, status: int, reason: str, headers: dict[str, str]) -> None:
140
+ self.status = status
141
+ self.reason = reason
142
+ self.headers = headers
143
+
144
+
145
+ async def _read_head(reader: asyncio.StreamReader) -> _Head:
146
+ raw = await reader.readuntil(b"\r\n\r\n")
147
+ lines = raw.decode("latin-1").split("\r\n")
148
+ parts = lines[0].split(" ", 2)
149
+ if len(parts) < 2 or not parts[0].startswith("HTTP/"):
150
+ raise DockerError(502, "the engine sent an answer that is not HTTP")
151
+ headers: dict[str, str] = {}
152
+ for line in lines[1:]:
153
+ if ":" in line:
154
+ name, _, value = line.partition(":")
155
+ headers[name.strip().lower()] = value.strip()
156
+ return _Head(int(parts[1]), parts[2] if len(parts) > 2 else "", headers)
157
+
158
+
159
+ #: One chunk of a chunked answer, and a whole buffered answer, are never larger than these (a misbehaving engine cannot
160
+ #: make the server hold more).
161
+ MAX_CHUNK = 16 * 1024 * 1024
162
+ MAX_BUFFERED = 64 * 1024 * 1024
163
+ MAX_REFUSAL = 64 * 1024
164
+
165
+
166
+ async def _iter_body(reader: asyncio.StreamReader, head: _Head) -> AsyncIterator[bytes]:
167
+ """The decoded body of an answer, piece by piece (chunked, by length, or until the connection closes)."""
168
+ if head.status in (204, 304) or 100 <= head.status < 200:
169
+ return
170
+ if "chunked" in head.headers.get("transfer-encoding", "").lower():
171
+ while True:
172
+ size_line = await reader.readline()
173
+ if not size_line:
174
+ # the connection ended where a chunk should begin: the body is not complete
175
+ raise asyncio.IncompleteReadError(b"", None)
176
+ try:
177
+ size = int(size_line.split(b";")[0].strip() or b"0", 16)
178
+ except ValueError:
179
+ # not a chunk size: the stream is broken, as if the connection had dropped
180
+ raise asyncio.IncompleteReadError(size_line, None) from None
181
+ if size < 0 or size > MAX_CHUNK:
182
+ raise DockerError(502, "the engine sent a chunk that is too large")
183
+ if size == 0:
184
+ # trailers, then the end
185
+ while True:
186
+ trailer = await reader.readline()
187
+ if trailer in (b"\r\n", b"\n", b""):
188
+ return
189
+ data = await reader.readexactly(size)
190
+ await reader.readexactly(2)
191
+ yield data
192
+ length = head.headers.get("content-length")
193
+ if length is not None:
194
+ try:
195
+ remaining = int(length)
196
+ except ValueError:
197
+ raise asyncio.IncompleteReadError(b"", None) from None
198
+ while remaining > 0:
199
+ data = await reader.read(min(65536, remaining))
200
+ if not data:
201
+ return
202
+ remaining -= len(data)
203
+ yield data
204
+ return
205
+ while True:
206
+ data = await reader.read(65536)
207
+ if not data:
208
+ return
209
+ yield data
210
+
211
+
212
+ def _close(writer: Optional[asyncio.StreamWriter]) -> None:
213
+ if writer is None:
214
+ return
215
+ try:
216
+ writer.close()
217
+ except Exception: # noqa: BLE001 - closing a dead connection
218
+ pass
219
+
220
+
221
+ class EngineStream:
222
+ """A streamed answer: iterate the decoded body; :meth:`close` ends it."""
223
+
224
+ def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, head: _Head) -> None:
225
+ self._reader = reader
226
+ self._writer = writer
227
+ self.status = head.status
228
+ self.headers = head.headers
229
+ self._head = head
230
+ #: True when the connection ended before the end of the body.
231
+ self.incomplete = False
232
+
233
+ def __aiter__(self) -> AsyncIterator[bytes]:
234
+ return self._chunks()
235
+
236
+ async def _chunks(self) -> AsyncIterator[bytes]:
237
+ try:
238
+ async for data in _iter_body(self._reader, self._head):
239
+ yield data
240
+ except (ConnectionError, asyncio.IncompleteReadError, ssl.SSLError):
241
+ self.incomplete = True
242
+ return
243
+ finally:
244
+ self.close()
245
+
246
+ def close(self) -> None:
247
+ _close(self._writer)
248
+
249
+
250
+ class EngineUpgrade:
251
+ """A hijacked connection (an exec): read what the engine sends, write the input, close."""
252
+
253
+ def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
254
+ self.reader = reader
255
+ self.writer = writer
256
+
257
+ async def read(self, n: int = 65536) -> bytes:
258
+ try:
259
+ return await self.reader.read(n)
260
+ except (ConnectionError, ssl.SSLError):
261
+ return b""
262
+
263
+ def write(self, data: bytes) -> None:
264
+ self.writer.write(data)
265
+
266
+ async def drain(self) -> None:
267
+ try:
268
+ await self.writer.drain()
269
+ except (ConnectionError, ssl.SSLError):
270
+ pass
271
+
272
+ def close(self) -> None:
273
+ _close(self.writer)
274
+
275
+
276
+ class EngineClient:
277
+ """A connection to one Docker host."""
278
+
279
+ def __init__(self, name: str, config: DockerHostConfig, default_timeout: float = 15.0) -> None:
280
+ #: The host's name, used in the messages.
281
+ self.name = name
282
+ self._config = config
283
+ self._timeout = default_timeout
284
+ self._endpoint = parse_endpoint(config)
285
+ self._tls_context: Optional[ssl.SSLContext] = None
286
+ self._tls_stamp: Any = None
287
+
288
+ @property
289
+ def display(self) -> str:
290
+ return self._endpoint.display
291
+
292
+ @property
293
+ def connection(self) -> dict[str, Any]:
294
+ """How a docker CLI reaches this host (the compose CLI is started with it)."""
295
+ e = self._endpoint
296
+ host = e.host or ""
297
+ return {
298
+ "unixPath": e.socket_path,
299
+ "tcp": None if e.socket_path else f"tcp://{'[' + host + ']' if ':' in host else host}:{e.port}",
300
+ "tls": e.protocol == "https",
301
+ "tlsVerify": self._config.tls_verify is not False,
302
+ "tlsCa": self._config.tls_ca,
303
+ "tlsCert": self._config.tls_cert,
304
+ "tlsKey": self._config.tls_key,
305
+ }
306
+
307
+ @property
308
+ def is_unix_socket(self) -> bool:
309
+ """Whether the host is a unix socket (the compose file can then be read from the server's disk)."""
310
+ return self._endpoint.socket_path is not None
311
+
312
+ # -- connections ---------------------------------------------------------------------------------------------
313
+
314
+ def _ssl_context(self) -> Optional[ssl.SSLContext]:
315
+ if self._endpoint.protocol != "https":
316
+ return None
317
+ stamp = self._tls_files_stamp()
318
+ if self._tls_context is not None and stamp == self._tls_stamp:
319
+ return self._tls_context
320
+ # The files are read here, in their own try: the error of a missing file names a path, which no text may show
321
+ try:
322
+ context = ssl.create_default_context(cafile=self._config.tls_ca) if self._config.tls_ca else ssl.create_default_context()
323
+ if self._config.tls_cert:
324
+ context.load_cert_chain(self._config.tls_cert, self._config.tls_key or None)
325
+ except (OSError, ssl.SSLError, ValueError) as err:
326
+ raise DockerError(502, f"cannot read the TLS files of {self.name}") from err
327
+ if self._config.tls_verify is False:
328
+ context.check_hostname = False
329
+ context.verify_mode = ssl.CERT_NONE
330
+ # built once per client; a replaced file (rotated certificate) makes a new one
331
+ self._tls_context, self._tls_stamp = context, stamp
332
+ return context
333
+
334
+ def _tls_files_stamp(self) -> tuple[Any, ...]:
335
+ stamp: list[Any] = []
336
+ for path in (self._config.tls_ca, self._config.tls_cert, self._config.tls_key):
337
+ try:
338
+ stamp.append(os.stat(path).st_mtime_ns if path else None)
339
+ except OSError:
340
+ stamp.append(-1)
341
+ return tuple(stamp)
342
+
343
+ async def _open(self) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
344
+ if self._endpoint.socket_path:
345
+ return await asyncio.open_unix_connection(self._endpoint.socket_path)
346
+ return await asyncio.open_connection(self._endpoint.host, self._endpoint.port, ssl=self._ssl_context())
347
+
348
+ def unreachable(self, err: BaseException) -> DockerError:
349
+ if isinstance(err, DockerError):
350
+ return err
351
+ return DockerError(502, f"cannot reach Docker at {self.name}: {network_message(err)}")
352
+
353
+ def _head_bytes(self, method: str, path: str, query: Optional[Mapping[str, Any]], body: Any, extra: Optional[Mapping[str, str]] = None) -> bytes:
354
+ headers = {"Host": "docker", "Connection": "close", "User-Agent": "qodalis-cli-docker"}
355
+ payload = b""
356
+ if body is not None:
357
+ payload = json.dumps(body, separators=(",", ":")).encode("utf-8")
358
+ headers["Content-Type"] = "application/json"
359
+ headers["Content-Length"] = str(len(payload))
360
+ elif method == "POST":
361
+ headers["Content-Length"] = "0"
362
+ headers.update(extra or {})
363
+ head = f"{method} {path}{query_string(query)} HTTP/1.1\r\n" + "".join(f"{k}: {v}\r\n" for k, v in headers.items()) + "\r\n"
364
+ return head.encode("latin-1") + payload
365
+
366
+ async def _refusal(self, reader: asyncio.StreamReader, head: _Head) -> DockerError:
367
+ chunks: list[bytes] = []
368
+ size = 0
369
+ try:
370
+ async for chunk in _iter_body(reader, head):
371
+ chunks.append(chunk)
372
+ size += len(chunk)
373
+ if size > MAX_REFUSAL:
374
+ break
375
+ except (DockerError, asyncio.IncompleteReadError, ConnectionError, ssl.SSLError):
376
+ pass # what arrived is the message
377
+ text = b"".join(chunks)[:MAX_REFUSAL].decode("utf-8", "replace").strip()
378
+ message = text
379
+ try:
380
+ parsed = json.loads(text)
381
+ if isinstance(parsed, dict) and isinstance(parsed.get("message"), str):
382
+ message = parsed["message"]
383
+ except ValueError:
384
+ pass
385
+ return DockerError(head.status, message or head.reason or f"the engine answered {head.status}")
386
+
387
+ # -- requests ------------------------------------------------------------------------------------------------
388
+
389
+ async def request(
390
+ self, method: str, path: str, *, query: Optional[Mapping[str, Any]] = None, body: Any = None,
391
+ timeout: Optional[float] = None, allow_304: bool = False,
392
+ ) -> EngineResponse:
393
+ """A request whose whole answer is buffered under one timeout; errors become :class:`DockerError`."""
394
+ writer: Optional[asyncio.StreamWriter] = None
395
+
396
+ async def run() -> EngineResponse:
397
+ nonlocal writer
398
+ reader, writer = await self._open()
399
+ writer.write(self._head_bytes(method, path, query, body))
400
+ await writer.drain()
401
+ head = await _read_head(reader)
402
+ if not 200 <= head.status < 300 and not (head.status == 304 and allow_304):
403
+ raise await self._refusal(reader, head)
404
+ pieces: list[bytes] = []
405
+ size = 0
406
+ async for piece in _iter_body(reader, head):
407
+ size += len(piece)
408
+ if size > MAX_BUFFERED:
409
+ raise DockerError(502, f"cannot reach Docker at {self.name}: the engine's answer is too large")
410
+ pieces.append(piece)
411
+ return EngineResponse(head.status, head.headers, b"".join(pieces))
412
+
413
+ try:
414
+ return await asyncio.wait_for(run(), timeout if timeout is not None else self._timeout)
415
+ except DockerError:
416
+ raise
417
+ except asyncio.CancelledError:
418
+ raise
419
+ except (asyncio.IncompleteReadError, asyncio.LimitOverrunError) as exc:
420
+ raise self.unreachable(exc) from exc
421
+ except Exception as exc: # noqa: BLE001 - every failure to talk to the engine is a 502
422
+ raise self.unreachable(exc) from exc
423
+ finally:
424
+ _close(writer)
425
+
426
+ async def json(
427
+ self, method: str, path: str, *, query: Optional[Mapping[str, Any]] = None, body: Any = None, timeout: Optional[float] = None,
428
+ ) -> Any:
429
+ res = await self.request(method, path, query=query, body=body, timeout=timeout)
430
+ if not res.body:
431
+ return None
432
+ try:
433
+ return json.loads(res.body.decode("utf-8"))
434
+ except ValueError as exc:
435
+ raise DockerError(502, f"cannot reach Docker at {self.name}: the engine sent an answer that is not JSON") from exc
436
+
437
+ async def stream(
438
+ self, method: str, path: str, *, query: Optional[Mapping[str, Any]] = None, body: Any = None, timeout: Optional[float] = None,
439
+ ) -> EngineStream:
440
+ """A streamed answer (logs, pulls, events): resolves at the response headers (under ``timeout``) with the stream to
441
+ read. A refusal of the engine raises with its status and message."""
442
+ writer: Optional[asyncio.StreamWriter] = None
443
+
444
+ async def run() -> EngineStream:
445
+ nonlocal writer
446
+ reader, writer = await self._open()
447
+ writer.write(self._head_bytes(method, path, query, body))
448
+ await writer.drain()
449
+ head = await _read_head(reader)
450
+ if not 200 <= head.status < 300:
451
+ raise await self._refusal(reader, head)
452
+ return EngineStream(reader, writer, head)
453
+
454
+ try:
455
+ return await asyncio.wait_for(run(), timeout if timeout is not None else self._timeout)
456
+ except BaseException as exc:
457
+ _close(writer)
458
+ if isinstance(exc, (DockerError, asyncio.CancelledError)):
459
+ raise
460
+ raise self.unreachable(exc) from exc
461
+
462
+ async def upgrade(self, path: str, body: Any, timeout: Optional[float] = None) -> EngineUpgrade:
463
+ """Hijacks the connection of a POST (an exec): resolves with the raw duplex after the ``101``."""
464
+ writer: Optional[asyncio.StreamWriter] = None
465
+
466
+ async def run() -> EngineUpgrade:
467
+ nonlocal writer
468
+ reader, writer = await self._open()
469
+ writer.write(self._head_bytes("POST", path, None, body, {"Connection": "Upgrade", "Upgrade": "tcp"}))
470
+ await writer.drain()
471
+ head = await _read_head(reader)
472
+ if head.status != 101:
473
+ raise await self._refusal(reader, head)
474
+ return EngineUpgrade(reader, writer)
475
+
476
+ try:
477
+ return await asyncio.wait_for(run(), timeout if timeout is not None else self._timeout)
478
+ except BaseException as exc:
479
+ _close(writer)
480
+ if isinstance(exc, (DockerError, asyncio.CancelledError)):
481
+ raise
482
+ raise self.unreachable(exc) from exc