| 1 |
# This code is part of the Ansible collection community.docker, but is an independent component. |
| 2 |
# This particular file, and this file only, is based on the Docker SDK for Python (https://github.com/docker/docker-py/) |
| 3 |
# |
| 4 |
# Copyright (c) 2016-2022 Docker, Inc. |
| 5 |
# |
| 6 |
# It is licensed under the Apache 2.0 license (see LICENSES/Apache-2.0.txt in this collection) |
| 7 |
# SPDX-License-Identifier: Apache-2.0 |
| 8 |
|
| 9 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 10 |
# Do not use this from other collections or standalone plugins/modules! |
| 11 |
|
| 12 |
from __future__ import annotations |
| 13 |
|
| 14 |
import json |
| 15 |
import logging |
| 16 |
import os |
| 17 |
import struct |
| 18 |
import typing as t |
| 19 |
from urllib.parse import quote |
| 20 |
|
| 21 |
from .. import auth |
| 22 |
from .._import_helper import HTTPError as _HTTPError |
| 23 |
from .._import_helper import InvalidSchema as _InvalidSchema |
| 24 |
from .._import_helper import Session as _Session |
| 25 |
from .._import_helper import fail_on_missing_imports |
| 26 |
from ..constants import ( |
| 27 |
DEFAULT_DATA_CHUNK_SIZE, |
| 28 |
DEFAULT_MAX_POOL_SIZE, |
| 29 |
DEFAULT_NUM_POOLS, |
| 30 |
DEFAULT_NUM_POOLS_SSH, |
| 31 |
DEFAULT_TIMEOUT_SECONDS, |
| 32 |
DEFAULT_USER_AGENT, |
| 33 |
IS_WINDOWS_PLATFORM, |
| 34 |
MINIMUM_DOCKER_API_VERSION, |
| 35 |
STREAM_HEADER_SIZE_BYTES, |
| 36 |
) |
| 37 |
from ..errors import ( |
| 38 |
DockerException, |
| 39 |
InvalidVersion, |
| 40 |
MissingRequirementException, |
| 41 |
TLSParameterError, |
| 42 |
create_api_error_from_http_exception, |
| 43 |
) |
| 44 |
from ..tls import TLSConfig |
| 45 |
from ..transport.npipeconn import NpipeHTTPAdapter |
| 46 |
from ..transport.npipesocket import PYWIN32_IMPORT_ERROR |
| 47 |
from ..transport.sshconn import PARAMIKO_IMPORT_ERROR, SSHHTTPAdapter |
| 48 |
from ..transport.ssladapter import SSLHTTPAdapter |
| 49 |
from ..transport.unixconn import UnixHTTPAdapter |
| 50 |
from ..utils import config, json_stream, utils |
| 51 |
from ..utils.decorators import minimum_version, update_headers |
| 52 |
from ..utils.proxy import ProxyConfig |
| 53 |
from ..utils.socket import consume_socket_output, demux_adaptor, frames_iter |
| 54 |
|
| 55 |
if t.TYPE_CHECKING: |
| 56 |
from requests import Response |
| 57 |
from requests.adapters import BaseAdapter |
| 58 |
|
| 59 |
from ..._socket_helper import SocketLike |
| 60 |
|
| 61 |
|
| 62 |
log = logging.getLogger(__name__) |
| 63 |
|
| 64 |
|
| 65 |
class APIClient(_Session): |
| 66 |
""" |
| 67 |
A low-level client for the Docker Engine API. |
| 68 |
|
| 69 |
Example: |
| 70 |
|
| 71 |
>>> import docker |
| 72 |
>>> client = docker.APIClient(base_url='unix://var/run/docker.sock') |
| 73 |
>>> client.version() |
| 74 |
{'ApiVersion': '1.33', |
| 75 |
'Arch': 'amd64', |
| 76 |
'BuildTime': '2017-11-19T18:46:37.000000000+00:00', |
| 77 |
'GitCommit': 'f4ffd2511c', |
| 78 |
'GoVersion': 'go1.9.2', |
| 79 |
'KernelVersion': '4.14.3-1-ARCH', |
| 80 |
'MinAPIVersion': '1.12', |
| 81 |
'Os': 'linux', |
| 82 |
'Version': '17.10.0-ce'} |
| 83 |
|
| 84 |
Args: |
| 85 |
base_url (str): URL to the Docker server. For example, |
| 86 |
``unix:///var/run/docker.sock`` or ``tcp://127.0.0.1:1234``. |
| 87 |
version (str): The version of the API to use. Set to ``auto`` to |
| 88 |
automatically detect the server's version. Default: ``1.35`` |
| 89 |
timeout (int): Default timeout for API calls, in seconds. |
| 90 |
tls (bool or :py:class:`~docker.tls.TLSConfig`): Enable TLS. Pass |
| 91 |
``True`` to enable it with default options, or pass a |
| 92 |
:py:class:`~docker.tls.TLSConfig` object to use custom |
| 93 |
configuration. |
| 94 |
user_agent (str): Set a custom user agent for requests to the server. |
| 95 |
credstore_env (dict): Override environment variables when calling the |
| 96 |
credential store process. |
| 97 |
use_ssh_client (bool): If set to `True`, an ssh connection is made |
| 98 |
via shelling out to the ssh client. Ensure the ssh client is |
| 99 |
installed and configured on the host. |
| 100 |
max_pool_size (int): The maximum number of connections |
| 101 |
to save in the pool. |
| 102 |
""" |
| 103 |
|
| 104 |
__attrs__ = _Session.__attrs__ + [ |
| 105 |
"_auth_configs", |
| 106 |
"_general_configs", |
| 107 |
"_version", |
| 108 |
"base_url", |
| 109 |
"timeout", |
| 110 |
] |
| 111 |
|
| 112 |
def __init__( |
| 113 |
self, |
| 114 |
base_url: str | None = None, |
| 115 |
version: str | None = None, |
| 116 |
timeout: int | float = DEFAULT_TIMEOUT_SECONDS, |
| 117 |
tls: bool | TLSConfig = False, |
| 118 |
user_agent: str = DEFAULT_USER_AGENT, |
| 119 |
num_pools: int | None = None, |
| 120 |
credstore_env: dict[str, str] | None = None, |
| 121 |
use_ssh_client: bool = False, |
| 122 |
max_pool_size: int = DEFAULT_MAX_POOL_SIZE, |
| 123 |
) -> None: |
| 124 |
super().__init__() |
| 125 |
|
| 126 |
fail_on_missing_imports() |
| 127 |
|
| 128 |
if tls and not base_url: |
| 129 |
raise TLSParameterError( |
| 130 |
"If using TLS, the base_url argument must be provided." |
| 131 |
) |
| 132 |
|
| 133 |
self.timeout = timeout |
| 134 |
self.headers["User-Agent"] = user_agent |
| 135 |
|
| 136 |
self._general_configs = config.load_general_config() |
| 137 |
|
| 138 |
proxy_config = self._general_configs.get("proxies", {}) |
| 139 |
try: |
| 140 |
proxies = proxy_config[base_url] |
| 141 |
except KeyError: |
| 142 |
proxies = proxy_config.get("default", {}) |
| 143 |
|
| 144 |
self._proxy_configs = ProxyConfig.from_dict(proxies) |
| 145 |
|
| 146 |
self._auth_configs = auth.load_config( |
| 147 |
config_dict=self._general_configs, |
| 148 |
credstore_env=credstore_env, |
| 149 |
) |
| 150 |
self.credstore_env = credstore_env |
| 151 |
|
| 152 |
base_url = utils.parse_host(base_url, IS_WINDOWS_PLATFORM, tls=bool(tls)) |
| 153 |
self.base_url = base_url |
| 154 |
# SSH has a different default for num_pools to all other adapters |
| 155 |
num_pools = ( |
| 156 |
num_pools or DEFAULT_NUM_POOLS_SSH |
| 157 |
if base_url.startswith("ssh://") |
| 158 |
else DEFAULT_NUM_POOLS |
| 159 |
) |
| 160 |
|
| 161 |
self._custom_adapter: ( |
| 162 |
UnixHTTPAdapter | NpipeHTTPAdapter | SSHHTTPAdapter | SSLHTTPAdapter | None |
| 163 |
) = None |
| 164 |
if base_url.startswith("http+unix://"): |
| 165 |
self._custom_adapter = UnixHTTPAdapter( |
| 166 |
base_url, |
| 167 |
timeout, |
| 168 |
pool_connections=num_pools, |
| 169 |
max_pool_size=max_pool_size, |
| 170 |
) |
| 171 |
self.mount("http+docker://", self._custom_adapter) |
| 172 |
self._unmount("http://", "https://") |
| 173 |
# host part of URL should be unused, but is resolved by requests |
| 174 |
# module in proxy_bypass_macosx_sysconf() |
| 175 |
self.base_url = "http+docker://localhost" |
| 176 |
elif base_url.startswith("npipe://"): |
| 177 |
if not IS_WINDOWS_PLATFORM: |
| 178 |
raise DockerException( |
| 179 |
"The npipe:// protocol is only supported on Windows" |
| 180 |
) |
| 181 |
if PYWIN32_IMPORT_ERROR is not None: |
| 182 |
raise MissingRequirementException( |
| 183 |
"Install pypiwin32 package to enable npipe:// support", |
| 184 |
"pywin32", |
| 185 |
PYWIN32_IMPORT_ERROR, |
| 186 |
) |
| 187 |
self._custom_adapter = NpipeHTTPAdapter( |
| 188 |
base_url, |
| 189 |
timeout, |
| 190 |
pool_connections=num_pools, |
| 191 |
max_pool_size=max_pool_size, |
| 192 |
) |
| 193 |
self.mount("http+docker://", self._custom_adapter) |
| 194 |
self.base_url = "http+docker://localnpipe" |
| 195 |
elif base_url.startswith("ssh://"): |
| 196 |
if PARAMIKO_IMPORT_ERROR is not None and not use_ssh_client: |
| 197 |
raise MissingRequirementException( |
| 198 |
"Install paramiko package to enable ssh:// support", |
| 199 |
"paramiko", |
| 200 |
PARAMIKO_IMPORT_ERROR, |
| 201 |
) |
| 202 |
self._custom_adapter = SSHHTTPAdapter( |
| 203 |
base_url, |
| 204 |
timeout, |
| 205 |
pool_connections=num_pools, |
| 206 |
max_pool_size=max_pool_size, |
| 207 |
shell_out=use_ssh_client, |
| 208 |
) |
| 209 |
self.mount("http+docker://ssh", self._custom_adapter) |
| 210 |
self._unmount("http://", "https://") |
| 211 |
self.base_url = "http+docker://ssh" |
| 212 |
else: |
| 213 |
# Use SSLAdapter for the ability to specify SSL version |
| 214 |
if isinstance(tls, TLSConfig): |
| 215 |
tls.configure_client(self) |
| 216 |
elif tls: |
| 217 |
self._custom_adapter = SSLHTTPAdapter(pool_connections=num_pools) |
| 218 |
self.mount("https://", self._custom_adapter) |
| 219 |
self.base_url = base_url |
| 220 |
|
| 221 |
# version detection needs to be after unix adapter mounting |
| 222 |
if version is None or (isinstance(version, str) and version.lower() == "auto"): |
| 223 |
self._version = self._retrieve_server_version() |
| 224 |
else: |
| 225 |
self._version = version |
| 226 |
if not isinstance(self._version, str): |
| 227 |
raise DockerException( |
| 228 |
f"Version parameter must be a string or None. Found {type(version).__name__}" |
| 229 |
) |
| 230 |
if utils.version_lt(self._version, MINIMUM_DOCKER_API_VERSION): |
| 231 |
raise InvalidVersion( |
| 232 |
f"API versions below {MINIMUM_DOCKER_API_VERSION} are no longer supported by this library." |
| 233 |
) |
| 234 |
|
| 235 |
def _retrieve_server_version(self) -> str: |
| 236 |
try: |
| 237 |
version_result = self.version(api_version=False) |
| 238 |
except Exception as e: |
| 239 |
raise DockerException( |
| 240 |
f"Error while fetching server API version: {e}" |
| 241 |
) from e |
| 242 |
|
| 243 |
try: |
| 244 |
return version_result["ApiVersion"] |
| 245 |
except KeyError: |
| 246 |
raise DockerException( |
| 247 |
'Invalid response from docker daemon: key "ApiVersion" is missing.' |
| 248 |
) from None |
| 249 |
except Exception as e: |
| 250 |
raise DockerException( |
| 251 |
f"Error while fetching server API version: {e}. Response seems to be broken." |
| 252 |
) from e |
| 253 |
|
| 254 |
def _set_request_timeout(self, kwargs: dict[str, t.Any]) -> dict[str, t.Any]: |
| 255 |
"""Prepare the kwargs for an HTTP request by inserting the timeout |
| 256 |
parameter, if not already present.""" |
| 257 |
kwargs.setdefault("timeout", self.timeout) |
| 258 |
return kwargs |
| 259 |
|
| 260 |
@update_headers |
| 261 |
def _post(self, url: str, **kwargs: t.Any) -> Response: |
| 262 |
return self.post(url, **self._set_request_timeout(kwargs)) |
| 263 |
|
| 264 |
@update_headers |
| 265 |
def _get(self, url: str, **kwargs: t.Any) -> Response: |
| 266 |
return self.get(url, **self._set_request_timeout(kwargs)) |
| 267 |
|
| 268 |
@update_headers |
| 269 |
def _head(self, url: str, **kwargs: t.Any) -> Response: |
| 270 |
return self.head(url, **self._set_request_timeout(kwargs)) |
| 271 |
|
| 272 |
@update_headers |
| 273 |
def _put(self, url: str, **kwargs: t.Any) -> Response: |
| 274 |
return self.put(url, **self._set_request_timeout(kwargs)) |
| 275 |
|
| 276 |
@update_headers |
| 277 |
def _delete(self, url: str, **kwargs: t.Any) -> Response: |
| 278 |
return self.delete(url, **self._set_request_timeout(kwargs)) |
| 279 |
|
| 280 |
def _url(self, pathfmt: str, *args: str, versioned_api: bool = True) -> str: |
| 281 |
for arg in args: |
| 282 |
if not isinstance(arg, str): |
| 283 |
raise ValueError( |
| 284 |
f"Expected a string but found {arg} ({type(arg)}) instead" |
| 285 |
) |
| 286 |
|
| 287 |
q_args = [quote(arg, safe="/:") for arg in args] |
| 288 |
|
| 289 |
if versioned_api: |
| 290 |
return f"{self.base_url}/v{self._version}{pathfmt.format(*q_args)}" |
| 291 |
return f"{self.base_url}{pathfmt.format(*q_args)}" |
| 292 |
|
| 293 |
def _raise_for_status(self, response: Response) -> None: |
| 294 |
"""Raises stored :class:`APIError`, if one occurred.""" |
| 295 |
try: |
| 296 |
response.raise_for_status() |
| 297 |
except _HTTPError as e: |
| 298 |
create_api_error_from_http_exception(e) |
| 299 |
|
| 300 |
@t.overload |
| 301 |
def _result( |
| 302 |
self, |
| 303 |
response: Response, |
| 304 |
*, |
| 305 |
get_json: t.Literal[False] = False, |
| 306 |
get_binary: t.Literal[False] = False, |
| 307 |
) -> str: ... |
| 308 |
|
| 309 |
@t.overload |
| 310 |
def _result( |
| 311 |
self, |
| 312 |
response: Response, |
| 313 |
*, |
| 314 |
get_json: t.Literal[True], |
| 315 |
get_binary: t.Literal[False] = False, |
| 316 |
) -> t.Any: ... |
| 317 |
|
| 318 |
@t.overload |
| 319 |
def _result( |
| 320 |
self, |
| 321 |
response: Response, |
| 322 |
*, |
| 323 |
get_json: t.Literal[False] = False, |
| 324 |
get_binary: t.Literal[True], |
| 325 |
) -> bytes: ... |
| 326 |
|
| 327 |
@t.overload |
| 328 |
def _result( |
| 329 |
self, response: Response, *, get_json: bool = False, get_binary: bool = False |
| 330 |
) -> t.Any | str | bytes: ... |
| 331 |
|
| 332 |
def _result( |
| 333 |
self, response: Response, *, get_json: bool = False, get_binary: bool = False |
| 334 |
) -> t.Any | str | bytes: |
| 335 |
if get_json and get_binary: |
| 336 |
raise AssertionError("json and binary must not be both True") |
| 337 |
self._raise_for_status(response) |
| 338 |
|
| 339 |
if get_json: |
| 340 |
return response.json() |
| 341 |
if get_binary: |
| 342 |
return response.content |
| 343 |
return response.text |
| 344 |
|
| 345 |
def _post_json( |
| 346 |
self, url: str, data: dict[str, str | None] | t.Any, **kwargs: t.Any |
| 347 |
) -> Response: |
| 348 |
# Go <1.1 cannot unserialize null to a string |
| 349 |
# so we do this disgusting thing here. |
| 350 |
data2: dict[str, t.Any] = {} |
| 351 |
if data is not None and isinstance(data, dict): |
| 352 |
for k, v in data.items(): |
| 353 |
if v is not None: |
| 354 |
data2[k] = v |
| 355 |
elif data is not None: |
| 356 |
data2 = data |
| 357 |
|
| 358 |
if "headers" not in kwargs: |
| 359 |
kwargs["headers"] = {} |
| 360 |
kwargs["headers"]["Content-Type"] = "application/json" |
| 361 |
return self._post(url, data=json.dumps(data2), **kwargs) |
| 362 |
|
| 363 |
def _attach_params(self, override: dict[str, int] | None = None) -> dict[str, int]: |
| 364 |
return override or {"stdout": 1, "stderr": 1, "stream": 1} |
| 365 |
|
| 366 |
def _get_raw_response_socket(self, response: Response) -> SocketLike: |
| 367 |
self._raise_for_status(response) |
| 368 |
if self.base_url == "http+docker://localnpipe": |
| 369 |
sock = response.raw._fp.fp.raw.sock # type: ignore[union-attr] |
| 370 |
elif self.base_url.startswith("http+docker://ssh"): |
| 371 |
sock = response.raw._fp.fp.channel # type: ignore[union-attr] |
| 372 |
else: |
| 373 |
sock = response.raw._fp.fp.raw # type: ignore[union-attr] |
| 374 |
if self.base_url.startswith("https://"): |
| 375 |
sock = sock._sock # type: ignore[union-attr] |
| 376 |
try: |
| 377 |
# Keep a reference to the response to stop it being garbage |
| 378 |
# collected. If the response is garbage collected, it will |
| 379 |
# close TLS sockets. |
| 380 |
sock._response = response |
| 381 |
except AttributeError: |
| 382 |
# UNIX sockets cannot have attributes set on them, but that's |
| 383 |
# fine because we will not be doing TLS over them |
| 384 |
pass |
| 385 |
|
| 386 |
return sock |
| 387 |
|
| 388 |
@t.overload |
| 389 |
def _stream_helper( |
| 390 |
self, response: Response, *, decode: t.Literal[False] = False |
| 391 |
) -> t.Generator[bytes | str]: ... |
| 392 |
|
| 393 |
@t.overload |
| 394 |
def _stream_helper( |
| 395 |
self, response: Response, *, decode: t.Literal[True] |
| 396 |
) -> t.Generator[t.Any]: ... |
| 397 |
|
| 398 |
def _stream_helper( |
| 399 |
self, response: Response, *, decode: bool = False |
| 400 |
) -> t.Generator[t.Any]: |
| 401 |
"""Generator for data coming from a chunked-encoded HTTP response.""" |
| 402 |
|
| 403 |
if response.raw._fp.chunked: # type: ignore[union-attr] |
| 404 |
if decode: |
| 405 |
yield from json_stream.json_stream( |
| 406 |
self._stream_helper(response, decode=False) |
| 407 |
) |
| 408 |
else: |
| 409 |
reader = response.raw |
| 410 |
while not reader.closed: |
| 411 |
# this read call will block until we get a chunk |
| 412 |
data = reader.read(1) |
| 413 |
if not data: |
| 414 |
break |
| 415 |
if reader._fp.chunk_left: # type: ignore[union-attr] |
| 416 |
data += reader.read(reader._fp.chunk_left) # type: ignore[union-attr] |
| 417 |
yield data |
| 418 |
else: |
| 419 |
# Response is not chunked, meaning we probably |
| 420 |
# encountered an error immediately |
| 421 |
yield self._result(response, get_json=decode) |
| 422 |
|
| 423 |
def _multiplexed_buffer_helper(self, response: Response) -> t.Generator[bytes]: |
| 424 |
"""A generator of multiplexed data blocks read from a buffered |
| 425 |
response.""" |
| 426 |
buf = self._result(response, get_binary=True) |
| 427 |
buf_length = len(buf) |
| 428 |
walker = 0 |
| 429 |
while True: |
| 430 |
if buf_length - walker < STREAM_HEADER_SIZE_BYTES: |
| 431 |
break |
| 432 |
header = buf[walker : walker + STREAM_HEADER_SIZE_BYTES] |
| 433 |
dummy, length = struct.unpack_from(">BxxxL", header) |
| 434 |
start = walker + STREAM_HEADER_SIZE_BYTES |
| 435 |
end = start + length |
| 436 |
walker = end |
| 437 |
yield buf[start:end] |
| 438 |
|
| 439 |
def _multiplexed_response_stream_helper( |
| 440 |
self, response: Response |
| 441 |
) -> t.Generator[bytes]: |
| 442 |
"""A generator of multiplexed data blocks coming from a response |
| 443 |
stream.""" |
| 444 |
|
| 445 |
# Disable timeout on the underlying socket to prevent |
| 446 |
# Read timed out(s) for long running processes |
| 447 |
socket = self._get_raw_response_socket(response) |
| 448 |
self._disable_socket_timeout(socket) |
| 449 |
|
| 450 |
while True: |
| 451 |
header = response.raw.read(STREAM_HEADER_SIZE_BYTES) |
| 452 |
if not header: |
| 453 |
break |
| 454 |
dummy, length = struct.unpack(">BxxxL", header) |
| 455 |
if not length: |
| 456 |
continue |
| 457 |
data = response.raw.read(length) |
| 458 |
if not data: |
| 459 |
break |
| 460 |
yield data |
| 461 |
|
| 462 |
@t.overload |
| 463 |
def _stream_raw_result( |
| 464 |
self, response: Response, *, chunk_size: int = 1, decode: t.Literal[True] = True |
| 465 |
) -> t.Generator[str]: ... |
| 466 |
|
| 467 |
@t.overload |
| 468 |
def _stream_raw_result( |
| 469 |
self, response: Response, *, chunk_size: int = 1, decode: t.Literal[False] |
| 470 |
) -> t.Generator[bytes]: ... |
| 471 |
|
| 472 |
def _stream_raw_result( |
| 473 |
self, response: Response, *, chunk_size: int = 1, decode: bool = True |
| 474 |
) -> t.Generator[str | bytes]: |
| 475 |
"""Stream result for TTY-enabled container and raw binary data""" |
| 476 |
self._raise_for_status(response) |
| 477 |
|
| 478 |
# Disable timeout on the underlying socket to prevent |
| 479 |
# Read timed out(s) for long running processes |
| 480 |
socket = self._get_raw_response_socket(response) |
| 481 |
self._disable_socket_timeout(socket) |
| 482 |
|
| 483 |
yield from response.iter_content(chunk_size, decode) |
| 484 |
|
| 485 |
@t.overload |
| 486 |
def _read_from_socket( |
| 487 |
self, |
| 488 |
response: Response, |
| 489 |
*, |
| 490 |
stream: t.Literal[True], |
| 491 |
tty: bool = True, |
| 492 |
demux: t.Literal[False] = False, |
| 493 |
) -> t.Generator[bytes]: ... |
| 494 |
|
| 495 |
@t.overload |
| 496 |
def _read_from_socket( |
| 497 |
self, |
| 498 |
response: Response, |
| 499 |
*, |
| 500 |
stream: t.Literal[True], |
| 501 |
tty: t.Literal[True] = True, |
| 502 |
demux: t.Literal[True], |
| 503 |
) -> t.Generator[tuple[bytes, None]]: ... |
| 504 |
|
| 505 |
@t.overload |
| 506 |
def _read_from_socket( |
| 507 |
self, |
| 508 |
response: Response, |
| 509 |
*, |
| 510 |
stream: t.Literal[True], |
| 511 |
tty: t.Literal[False], |
| 512 |
demux: t.Literal[True], |
| 513 |
) -> t.Generator[tuple[bytes, None] | tuple[None, bytes]]: ... |
| 514 |
|
| 515 |
@t.overload |
| 516 |
def _read_from_socket( |
| 517 |
self, |
| 518 |
response: Response, |
| 519 |
*, |
| 520 |
stream: t.Literal[False], |
| 521 |
tty: bool = True, |
| 522 |
demux: t.Literal[False] = False, |
| 523 |
) -> bytes: ... |
| 524 |
|
| 525 |
@t.overload |
| 526 |
def _read_from_socket( |
| 527 |
self, |
| 528 |
response: Response, |
| 529 |
*, |
| 530 |
stream: t.Literal[False], |
| 531 |
tty: t.Literal[True] = True, |
| 532 |
demux: t.Literal[True], |
| 533 |
) -> tuple[bytes, None]: ... |
| 534 |
|
| 535 |
@t.overload |
| 536 |
def _read_from_socket( |
| 537 |
self, |
| 538 |
response: Response, |
| 539 |
*, |
| 540 |
stream: t.Literal[False], |
| 541 |
tty: t.Literal[False], |
| 542 |
demux: t.Literal[True], |
| 543 |
) -> tuple[bytes, bytes]: ... |
| 544 |
|
| 545 |
@t.overload |
| 546 |
def _read_from_socket( |
| 547 |
self, response: Response, *, stream: bool, tty: bool = True, demux: bool = False |
| 548 |
) -> t.Any: ... |
| 549 |
|
| 550 |
def _read_from_socket( |
| 551 |
self, response: Response, *, stream: bool, tty: bool = True, demux: bool = False |
| 552 |
) -> t.Any: |
| 553 |
"""Consume all data from the socket, close the response and return the |
| 554 |
data. If stream=True, then a generator is returned instead and the |
| 555 |
caller is responsible for closing the response. |
| 556 |
""" |
| 557 |
socket = self._get_raw_response_socket(response) |
| 558 |
|
| 559 |
gen = frames_iter(socket, tty) |
| 560 |
|
| 561 |
if demux: |
| 562 |
# The generator will output tuples (stdout, stderr) |
| 563 |
demux_gen: t.Generator[tuple[bytes | None, bytes | None]] = ( |
| 564 |
demux_adaptor(*frame) for frame in gen |
| 565 |
) |
| 566 |
if stream: |
| 567 |
return demux_gen |
| 568 |
try: |
| 569 |
# Wait for all the frames, concatenate them, and return the result |
| 570 |
return consume_socket_output(demux_gen, demux=True) |
| 571 |
finally: |
| 572 |
response.close() |
| 573 |
else: |
| 574 |
# The generator will output strings |
| 575 |
mux_gen: t.Generator[bytes] = (data for (dummy, data) in gen) |
| 576 |
if stream: |
| 577 |
return mux_gen |
| 578 |
try: |
| 579 |
# Wait for all the frames, concatenate them, and return the result |
| 580 |
return consume_socket_output(mux_gen, demux=False) |
| 581 |
finally: |
| 582 |
response.close() |
| 583 |
|
| 584 |
def _disable_socket_timeout(self, socket: SocketLike) -> None: |
| 585 |
"""Depending on the combination of python version and whether we are |
| 586 |
connecting over http or https, we might need to access _sock, which |
| 587 |
may or may not exist; or we may need to just settimeout on socket |
| 588 |
itself, which also may or may not have settimeout on it. To avoid |
| 589 |
missing the correct one, we try both. |
| 590 |
|
| 591 |
We also do not want to set the timeout if it is already disabled, as |
| 592 |
you run the risk of changing a socket that was non-blocking to |
| 593 |
blocking, for example when using gevent. |
| 594 |
""" |
| 595 |
sockets = [socket, getattr(socket, "_sock", None)] |
| 596 |
|
| 597 |
for s in sockets: |
| 598 |
if not hasattr(s, "settimeout"): |
| 599 |
continue |
| 600 |
|
| 601 |
timeout: int | float | None = -1 |
| 602 |
|
| 603 |
if hasattr(s, "gettimeout"): |
| 604 |
timeout = s.gettimeout() # type: ignore[union-attr] |
| 605 |
|
| 606 |
# Do not change the timeout if it is already disabled. |
| 607 |
if timeout is None or timeout == 0.0: |
| 608 |
continue |
| 609 |
|
| 610 |
s.settimeout(None) # type: ignore[union-attr] |
| 611 |
|
| 612 |
@t.overload |
| 613 |
def _get_result_tty( |
| 614 |
self, stream: t.Literal[True], res: Response, is_tty: t.Literal[True] |
| 615 |
) -> t.Generator[str]: ... |
| 616 |
|
| 617 |
@t.overload |
| 618 |
def _get_result_tty( |
| 619 |
self, stream: t.Literal[True], res: Response, is_tty: t.Literal[False] |
| 620 |
) -> t.Generator[bytes]: ... |
| 621 |
|
| 622 |
@t.overload |
| 623 |
def _get_result_tty( |
| 624 |
self, stream: t.Literal[False], res: Response, is_tty: t.Literal[True] |
| 625 |
) -> bytes: ... |
| 626 |
|
| 627 |
@t.overload |
| 628 |
def _get_result_tty( |
| 629 |
self, stream: t.Literal[False], res: Response, is_tty: t.Literal[False] |
| 630 |
) -> bytes: ... |
| 631 |
|
| 632 |
def _get_result_tty(self, stream: bool, res: Response, is_tty: bool) -> t.Any: |
| 633 |
# We should also use raw streaming (without keep-alive) |
| 634 |
# if we are dealing with a tty-enabled container. |
| 635 |
if is_tty: |
| 636 |
return ( |
| 637 |
self._stream_raw_result(res) |
| 638 |
if stream |
| 639 |
else self._result(res, get_binary=True) |
| 640 |
) |
| 641 |
|
| 642 |
self._raise_for_status(res) |
| 643 |
sep = b"" |
| 644 |
if stream: |
| 645 |
return self._multiplexed_response_stream_helper(res) |
| 646 |
return sep.join(list(self._multiplexed_buffer_helper(res))) |
| 647 |
|
| 648 |
def _unmount(self, *args: t.Any) -> None: |
| 649 |
for proto in args: |
| 650 |
self.adapters.pop(proto) |
| 651 |
|
| 652 |
def get_adapter(self, url: str) -> BaseAdapter: |
| 653 |
try: |
| 654 |
# pylint finds our Session stub instead of requests.Session: |
| 655 |
# pylint: disable-next=no-member |
| 656 |
return super().get_adapter(url) |
| 657 |
except _InvalidSchema as e: |
| 658 |
if self._custom_adapter: |
| 659 |
return self._custom_adapter |
| 660 |
raise e |
| 661 |
|
| 662 |
@property |
| 663 |
def api_version(self) -> str: |
| 664 |
return self._version |
| 665 |
|
| 666 |
def reload_config(self, dockercfg_path: str | None = None) -> None: |
| 667 |
""" |
| 668 |
Force a reload of the auth configuration |
| 669 |
|
| 670 |
Args: |
| 671 |
dockercfg_path (str): Use a custom path for the Docker config file |
| 672 |
(default ``$HOME/.docker/config.json`` if present, |
| 673 |
otherwise ``$HOME/.dockercfg``) |
| 674 |
|
| 675 |
Returns: |
| 676 |
None |
| 677 |
""" |
| 678 |
self._auth_configs = auth.load_config( |
| 679 |
dockercfg_path, credstore_env=self.credstore_env |
| 680 |
) |
| 681 |
|
| 682 |
def _set_auth_headers(self, headers: dict[str, str | bytes]) -> None: |
| 683 |
log.debug("Looking for auth config") |
| 684 |
|
| 685 |
# If we do not have any auth data so far, try reloading the config |
| 686 |
# file one more time in case anything showed up in there. |
| 687 |
if not self._auth_configs or self._auth_configs.is_empty: |
| 688 |
log.debug("No auth config in memory - loading from filesystem") |
| 689 |
self._auth_configs = auth.load_config(credstore_env=self.credstore_env) |
| 690 |
|
| 691 |
# Send the full auth configuration (if any exists), since the build |
| 692 |
# could use any (or all) of the registries. |
| 693 |
if self._auth_configs: |
| 694 |
auth_data = self._auth_configs.get_all_credentials() |
| 695 |
|
| 696 |
# See https://github.com/docker/docker-py/issues/1683 |
| 697 |
if auth.INDEX_URL not in auth_data and auth.INDEX_NAME in auth_data: |
| 698 |
auth_data[auth.INDEX_URL] = auth_data.get(auth.INDEX_NAME, {}) |
| 699 |
|
| 700 |
log.debug("Sending auth config (%s)", ", ".join(repr(k) for k in auth_data)) |
| 701 |
|
| 702 |
if auth_data: |
| 703 |
headers["X-Registry-Config"] = auth.encode_header(auth_data) |
| 704 |
else: |
| 705 |
log.debug("No auth config found") |
| 706 |
|
| 707 |
def get_binary(self, pathfmt: str, *args: str, **kwargs: t.Any) -> bytes: |
| 708 |
return self._result( |
| 709 |
self._get(self._url(pathfmt, *args, versioned_api=True), **kwargs), |
| 710 |
get_binary=True, |
| 711 |
) |
| 712 |
|
| 713 |
def get_json(self, pathfmt: str, *args: str, **kwargs: t.Any) -> t.Any: |
| 714 |
return self._result( |
| 715 |
self._get(self._url(pathfmt, *args, versioned_api=True), **kwargs), |
| 716 |
get_json=True, |
| 717 |
) |
| 718 |
|
| 719 |
def get_text(self, pathfmt: str, *args: str, **kwargs: t.Any) -> str: |
| 720 |
return self._result( |
| 721 |
self._get(self._url(pathfmt, *args, versioned_api=True), **kwargs) |
| 722 |
) |
| 723 |
|
| 724 |
def get_raw_stream( |
| 725 |
self, |
| 726 |
pathfmt: str, |
| 727 |
*args: str, |
| 728 |
chunk_size: int = DEFAULT_DATA_CHUNK_SIZE, |
| 729 |
**kwargs: t.Any, |
| 730 |
) -> t.Generator[bytes]: |
| 731 |
res = self._get( |
| 732 |
self._url(pathfmt, *args, versioned_api=True), stream=True, **kwargs |
| 733 |
) |
| 734 |
self._raise_for_status(res) |
| 735 |
return self._stream_raw_result(res, chunk_size=chunk_size, decode=False) |
| 736 |
|
| 737 |
def delete_call(self, pathfmt: str, *args: str, **kwargs: t.Any) -> None: |
| 738 |
self._raise_for_status( |
| 739 |
self._delete(self._url(pathfmt, *args, versioned_api=True), **kwargs) |
| 740 |
) |
| 741 |
|
| 742 |
def delete_json(self, pathfmt: str, *args: str, **kwargs: t.Any) -> t.Any: |
| 743 |
return self._result( |
| 744 |
self._delete(self._url(pathfmt, *args, versioned_api=True), **kwargs), |
| 745 |
get_json=True, |
| 746 |
) |
| 747 |
|
| 748 |
def post_call(self, pathfmt: str, *args: str, **kwargs: t.Any) -> None: |
| 749 |
self._raise_for_status( |
| 750 |
self._post(self._url(pathfmt, *args, versioned_api=True), **kwargs) |
| 751 |
) |
| 752 |
|
| 753 |
def post_json( |
| 754 |
self, pathfmt: str, *args: str, data: t.Any = None, **kwargs: t.Any |
| 755 |
) -> None: |
| 756 |
self._raise_for_status( |
| 757 |
self._post_json( |
| 758 |
self._url(pathfmt, *args, versioned_api=True), data, **kwargs |
| 759 |
) |
| 760 |
) |
| 761 |
|
| 762 |
def post_json_to_binary( |
| 763 |
self, pathfmt: str, *args: str, data: t.Any = None, **kwargs: t.Any |
| 764 |
) -> bytes: |
| 765 |
return self._result( |
| 766 |
self._post_json( |
| 767 |
self._url(pathfmt, *args, versioned_api=True), data, **kwargs |
| 768 |
), |
| 769 |
get_binary=True, |
| 770 |
) |
| 771 |
|
| 772 |
def post_json_to_json( |
| 773 |
self, pathfmt: str, *args: str, data: t.Any = None, **kwargs: t.Any |
| 774 |
) -> t.Any: |
| 775 |
return self._result( |
| 776 |
self._post_json( |
| 777 |
self._url(pathfmt, *args, versioned_api=True), data, **kwargs |
| 778 |
), |
| 779 |
get_json=True, |
| 780 |
) |
| 781 |
|
| 782 |
def post_json_to_text( |
| 783 |
self, pathfmt: str, *args: str, data: t.Any = None, **kwargs: t.Any |
| 784 |
) -> str: |
| 785 |
return self._result( |
| 786 |
self._post_json( |
| 787 |
self._url(pathfmt, *args, versioned_api=True), data, **kwargs |
| 788 |
), |
| 789 |
) |
| 790 |
|
| 791 |
def post_json_to_stream_socket( |
| 792 |
self, |
| 793 |
pathfmt: str, |
| 794 |
*args: str, |
| 795 |
data: t.Any = None, |
| 796 |
headers: dict[str, str] | None = None, |
| 797 |
**kwargs: t.Any, |
| 798 |
) -> SocketLike: |
| 799 |
headers = headers.copy() if headers else {} |
| 800 |
headers.update( |
| 801 |
{ |
| 802 |
"Connection": "Upgrade", |
| 803 |
"Upgrade": "tcp", |
| 804 |
} |
| 805 |
) |
| 806 |
return self._get_raw_response_socket( |
| 807 |
self._post_json( |
| 808 |
self._url(pathfmt, *args, versioned_api=True), |
| 809 |
data, |
| 810 |
headers=headers, |
| 811 |
stream=True, |
| 812 |
**kwargs, |
| 813 |
) |
| 814 |
) |
| 815 |
|
| 816 |
@t.overload |
| 817 |
def post_json_to_stream( |
| 818 |
self, |
| 819 |
pathfmt: str, |
| 820 |
*args: str, |
| 821 |
data: t.Any = None, |
| 822 |
headers: dict[str, str] | None = None, |
| 823 |
stream: t.Literal[True], |
| 824 |
tty: bool = True, |
| 825 |
demux: t.Literal[False] = False, |
| 826 |
**kwargs: t.Any, |
| 827 |
) -> t.Generator[bytes]: ... |
| 828 |
|
| 829 |
@t.overload |
| 830 |
def post_json_to_stream( |
| 831 |
self, |
| 832 |
pathfmt: str, |
| 833 |
*args: str, |
| 834 |
data: t.Any = None, |
| 835 |
headers: dict[str, str] | None = None, |
| 836 |
stream: t.Literal[True], |
| 837 |
tty: t.Literal[True] = True, |
| 838 |
demux: t.Literal[True], |
| 839 |
**kwargs: t.Any, |
| 840 |
) -> t.Generator[tuple[bytes, None]]: ... |
| 841 |
|
| 842 |
@t.overload |
| 843 |
def post_json_to_stream( |
| 844 |
self, |
| 845 |
pathfmt: str, |
| 846 |
*args: str, |
| 847 |
data: t.Any = None, |
| 848 |
headers: dict[str, str] | None = None, |
| 849 |
stream: t.Literal[True], |
| 850 |
tty: t.Literal[False], |
| 851 |
demux: t.Literal[True], |
| 852 |
**kwargs: t.Any, |
| 853 |
) -> t.Generator[tuple[bytes, None] | tuple[None, bytes]]: ... |
| 854 |
|
| 855 |
@t.overload |
| 856 |
def post_json_to_stream( |
| 857 |
self, |
| 858 |
pathfmt: str, |
| 859 |
*args: str, |
| 860 |
data: t.Any = None, |
| 861 |
headers: dict[str, str] | None = None, |
| 862 |
stream: t.Literal[False], |
| 863 |
tty: bool = True, |
| 864 |
demux: t.Literal[False] = False, |
| 865 |
**kwargs: t.Any, |
| 866 |
) -> bytes: ... |
| 867 |
|
| 868 |
@t.overload |
| 869 |
def post_json_to_stream( |
| 870 |
self, |
| 871 |
pathfmt: str, |
| 872 |
*args: str, |
| 873 |
data: t.Any = None, |
| 874 |
headers: dict[str, str] | None = None, |
| 875 |
stream: t.Literal[False], |
| 876 |
tty: t.Literal[True] = True, |
| 877 |
demux: t.Literal[True], |
| 878 |
**kwargs: t.Any, |
| 879 |
) -> tuple[bytes, None]: ... |
| 880 |
|
| 881 |
@t.overload |
| 882 |
def post_json_to_stream( |
| 883 |
self, |
| 884 |
pathfmt: str, |
| 885 |
*args: str, |
| 886 |
data: t.Any = None, |
| 887 |
headers: dict[str, str] | None = None, |
| 888 |
stream: t.Literal[False], |
| 889 |
tty: t.Literal[False], |
| 890 |
demux: t.Literal[True], |
| 891 |
**kwargs: t.Any, |
| 892 |
) -> tuple[bytes, bytes]: ... |
| 893 |
|
| 894 |
def post_json_to_stream( |
| 895 |
self, |
| 896 |
pathfmt: str, |
| 897 |
*args: str, |
| 898 |
data: t.Any = None, |
| 899 |
headers: dict[str, str] | None = None, |
| 900 |
stream: bool = False, |
| 901 |
demux: bool = False, |
| 902 |
tty: bool = False, |
| 903 |
**kwargs: t.Any, |
| 904 |
) -> t.Any: |
| 905 |
headers = headers.copy() if headers else {} |
| 906 |
headers.update( |
| 907 |
{ |
| 908 |
"Connection": "Upgrade", |
| 909 |
"Upgrade": "tcp", |
| 910 |
} |
| 911 |
) |
| 912 |
return self._read_from_socket( |
| 913 |
self._post_json( |
| 914 |
self._url(pathfmt, *args, versioned_api=True), |
| 915 |
data, |
| 916 |
headers=headers, |
| 917 |
stream=True, |
| 918 |
**kwargs, |
| 919 |
), |
| 920 |
stream=stream, |
| 921 |
tty=tty, |
| 922 |
demux=demux, |
| 923 |
) |
| 924 |
|
| 925 |
def post_to_json(self, pathfmt: str, *args: str, **kwargs: t.Any) -> t.Any: |
| 926 |
return self._result( |
| 927 |
self._post(self._url(pathfmt, *args, versioned_api=True), **kwargs), |
| 928 |
get_json=True, |
| 929 |
) |
| 930 |
|
| 931 |
@minimum_version("1.25") |
| 932 |
def df(self) -> dict[str, t.Any]: |
| 933 |
""" |
| 934 |
Get data usage information. |
| 935 |
|
| 936 |
Returns: |
| 937 |
(dict): A dictionary representing different resource categories |
| 938 |
and their respective data usage. |
| 939 |
|
| 940 |
Raises: |
| 941 |
:py:class:`docker.errors.APIError` |
| 942 |
If the server returns an error. |
| 943 |
""" |
| 944 |
url = self._url("/system/df") |
| 945 |
return self._result(self._get(url), get_json=True) |
| 946 |
|
| 947 |
def info(self) -> dict[str, t.Any]: |
| 948 |
""" |
| 949 |
Display system-wide information. Identical to the ``docker info`` |
| 950 |
command. |
| 951 |
|
| 952 |
Returns: |
| 953 |
(dict): The info as a dict |
| 954 |
|
| 955 |
Raises: |
| 956 |
:py:class:`docker.errors.APIError` |
| 957 |
If the server returns an error. |
| 958 |
""" |
| 959 |
return self._result(self._get(self._url("/info")), get_json=True) |
| 960 |
|
| 961 |
def login( |
| 962 |
self, |
| 963 |
username: str, |
| 964 |
password: str | None = None, |
| 965 |
email: str | None = None, |
| 966 |
registry: str | None = None, |
| 967 |
reauth: bool = False, |
| 968 |
dockercfg_path: str | None = None, |
| 969 |
) -> dict[str, t.Any]: |
| 970 |
""" |
| 971 |
Authenticate with a registry. Similar to the ``docker login`` command. |
| 972 |
|
| 973 |
Args: |
| 974 |
username (str): The registry username |
| 975 |
password (str): The plaintext password |
| 976 |
email (str): The email for the registry account |
| 977 |
registry (str): URL to the registry. E.g. |
| 978 |
``https://index.docker.io/v1/`` |
| 979 |
reauth (bool): Whether or not to refresh existing authentication on |
| 980 |
the Docker server. |
| 981 |
dockercfg_path (str): Use a custom path for the Docker config file |
| 982 |
(default ``$HOME/.docker/config.json`` if present, |
| 983 |
otherwise ``$HOME/.dockercfg``) |
| 984 |
|
| 985 |
Returns: |
| 986 |
(dict): The response from the login request |
| 987 |
|
| 988 |
Raises: |
| 989 |
:py:class:`docker.errors.APIError` |
| 990 |
If the server returns an error. |
| 991 |
""" |
| 992 |
|
| 993 |
# If we do not have any auth data so far, try reloading the config file |
| 994 |
# one more time in case anything showed up in there. |
| 995 |
# If dockercfg_path is passed check to see if the config file exists, |
| 996 |
# if so load that config. |
| 997 |
if dockercfg_path and os.path.exists(dockercfg_path): |
| 998 |
self._auth_configs = auth.load_config( |
| 999 |
dockercfg_path, credstore_env=self.credstore_env |
| 1000 |
) |
| 1001 |
elif not self._auth_configs or self._auth_configs.is_empty: |
| 1002 |
self._auth_configs = auth.load_config(credstore_env=self.credstore_env) |
| 1003 |
|
| 1004 |
authcfg = self._auth_configs.resolve_authconfig(registry) |
| 1005 |
# If we found an existing auth config for this registry and username |
| 1006 |
# combination, we can return it immediately unless reauth is requested. |
| 1007 |
if authcfg and authcfg.get("username", None) == username and not reauth: |
| 1008 |
return authcfg |
| 1009 |
|
| 1010 |
req_data = { |
| 1011 |
"username": username, |
| 1012 |
"password": password, |
| 1013 |
"email": email, |
| 1014 |
"serveraddress": registry, |
| 1015 |
} |
| 1016 |
|
| 1017 |
response = self._post_json(self._url("/auth"), data=req_data) |
| 1018 |
if response.status_code == 200: |
| 1019 |
self._auth_configs.add_auth(registry or auth.INDEX_NAME, req_data) |
| 1020 |
return self._result(response, get_json=True) |
| 1021 |
|
| 1022 |
def ping(self) -> bool: |
| 1023 |
""" |
| 1024 |
Checks the server is responsive. An exception will be raised if it |
| 1025 |
is not responding. |
| 1026 |
|
| 1027 |
Returns: |
| 1028 |
(bool) The response from the server. |
| 1029 |
|
| 1030 |
Raises: |
| 1031 |
:py:class:`docker.errors.APIError` |
| 1032 |
If the server returns an error. |
| 1033 |
""" |
| 1034 |
return self._result(self._get(self._url("/_ping"))) == "OK" |
| 1035 |
|
| 1036 |
def version(self, api_version: bool = True) -> dict[str, t.Any]: |
| 1037 |
""" |
| 1038 |
Returns version information from the server. Similar to the ``docker |
| 1039 |
version`` command. |
| 1040 |
|
| 1041 |
Returns: |
| 1042 |
(dict): The server version information |
| 1043 |
|
| 1044 |
Raises: |
| 1045 |
:py:class:`docker.errors.APIError` |
| 1046 |
If the server returns an error. |
| 1047 |
""" |
| 1048 |
url = self._url("/version", versioned_api=api_version) |
| 1049 |
return self._result(self._get(url), get_json=True) |