Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_api/transport/npipeconn.py

raw
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 typing as t
15 from queue import Empty
16
17 from .. import constants
18 from .._import_helper import HTTPAdapter, urllib3, urllib3_connection
19 from .basehttpadapter import BaseHTTPAdapter
20 from .npipesocket import NpipeSocket
21
22 if t.TYPE_CHECKING:
23 from collections.abc import Mapping
24
25 from requests import PreparedRequest
26
27
28 RecentlyUsedContainer = urllib3._collections.RecentlyUsedContainer
29
30
31 class NpipeHTTPConnection(urllib3_connection.HTTPConnection):
32 def __init__(self, npipe_path: str, timeout: int | float = 60) -> None:
33 super().__init__("localhost", timeout=timeout)
34 self.npipe_path = npipe_path
35 self.timeout = timeout
36
37 def connect(self) -> None:
38 sock = NpipeSocket()
39 sock.settimeout(self.timeout)
40 sock.connect(self.npipe_path)
41 self.sock = sock
42
43
44 class NpipeHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
45 def __init__(
46 self, npipe_path: str, timeout: int | float = 60, maxsize: int = 10
47 ) -> None:
48 super().__init__("localhost", timeout=timeout, maxsize=maxsize)
49 self.npipe_path = npipe_path
50 self.timeout = timeout
51
52 def _new_conn(self) -> NpipeHTTPConnection:
53 return NpipeHTTPConnection(self.npipe_path, self.timeout)
54
55 # When re-using connections, urllib3 tries to call select() on our
56 # NpipeSocket instance, causing a crash. To circumvent this, we override
57 # _get_conn, where that check happens.
58 def _get_conn(self, timeout: int | float) -> NpipeHTTPConnection:
59 conn = None
60 try:
61 conn = self.pool.get(block=self.block, timeout=timeout)
62
63 except AttributeError as exc: # self.pool is None
64 raise urllib3.exceptions.ClosedPoolError(self, "Pool is closed.") from exc
65
66 except Empty as exc:
67 if self.block:
68 raise urllib3.exceptions.EmptyPoolError(
69 self,
70 "Pool reached maximum size and no more connections are allowed.",
71 ) from exc
72 # Oh well, we'll create a new connection then
73
74 return conn or self._new_conn()
75
76
77 class NpipeHTTPAdapter(BaseHTTPAdapter):
78 __attrs__ = HTTPAdapter.__attrs__ + [
79 "npipe_path",
80 "pools",
81 "timeout",
82 "max_pool_size",
83 ]
84
85 def __init__(
86 self,
87 base_url: str,
88 timeout: int | float = 60,
89 pool_connections: int = constants.DEFAULT_NUM_POOLS,
90 max_pool_size: int = constants.DEFAULT_MAX_POOL_SIZE,
91 ) -> None:
92 self.npipe_path = base_url.replace("npipe://", "")
93 self.timeout = timeout
94 self.max_pool_size = max_pool_size
95 self.pools = RecentlyUsedContainer(
96 pool_connections, dispose_func=lambda p: p.close()
97 )
98 super().__init__()
99
100 def get_connection(
101 self, url: str | bytes, proxies: Mapping[str, str] | None = None
102 ) -> NpipeHTTPConnectionPool:
103 with self.pools.lock:
104 pool = self.pools.get(url)
105 if pool:
106 return pool
107
108 pool = NpipeHTTPConnectionPool(
109 self.npipe_path, self.timeout, maxsize=self.max_pool_size
110 )
111 self.pools[url] = pool
112
113 return pool
114
115 def request_url(
116 self, request: PreparedRequest, proxies: Mapping[str, str] | None
117 ) -> str:
118 # The select_proxy utility in requests errors out when the provided URL
119 # does not have a hostname, like is the case when using a UNIX socket.
120 # Since proxies are an irrelevant notion in the case of UNIX sockets
121 # anyway, we simply return the path URL directly.
122 # See also: https://github.com/docker/docker-sdk-python/issues/811
123 return request.path_url