Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_api/transport/unixconn.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 socket
15 import typing as t
16
17 from .. import constants
18 from .._import_helper import HTTPAdapter, urllib3, urllib3_connection
19 from .basehttpadapter import BaseHTTPAdapter
20
21 if t.TYPE_CHECKING:
22 from collections.abc import Mapping
23
24 from requests import PreparedRequest
25
26 from ..._socket_helper import SocketLike
27
28
29 RecentlyUsedContainer = urllib3._collections.RecentlyUsedContainer
30
31
32 class UnixHTTPConnection(urllib3_connection.HTTPConnection):
33 def __init__(
34 self, base_url: str | bytes, unix_socket: str, timeout: int | float = 60
35 ) -> None:
36 super().__init__("localhost", timeout=timeout)
37 self.base_url = base_url
38 self.unix_socket = unix_socket
39 self.timeout = timeout
40 self.disable_buffering = False
41
42 def connect(self) -> None:
43 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
44 sock.settimeout(self.timeout)
45 sock.connect(self.unix_socket)
46 self.sock = sock
47
48 def putheader(self, header: str, *values: str) -> None:
49 super().putheader(header, *values)
50 if header == "Connection" and "Upgrade" in values:
51 self.disable_buffering = True
52
53 def response_class(self, sock: SocketLike, *args: t.Any, **kwargs: t.Any) -> t.Any:
54 # FIXME: We may need to disable buffering on Py3,
55 # but there's no clear way to do it at the moment. See:
56 # https://github.com/docker/docker-py/issues/1799
57 return super().response_class(sock, *args, **kwargs)
58
59
60 class UnixHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
61 def __init__(
62 self,
63 base_url: str | bytes,
64 socket_path: str,
65 timeout: int | float = 60,
66 maxsize: int = 10,
67 ) -> None:
68 super().__init__("localhost", timeout=timeout, maxsize=maxsize)
69 self.base_url = base_url
70 self.socket_path = socket_path
71 self.timeout = timeout
72
73 def _new_conn(self) -> UnixHTTPConnection:
74 return UnixHTTPConnection(self.base_url, self.socket_path, self.timeout)
75
76
77 class UnixHTTPAdapter(BaseHTTPAdapter):
78 __attrs__ = HTTPAdapter.__attrs__ + [
79 "pools",
80 "socket_path",
81 "timeout",
82 "max_pool_size",
83 ]
84
85 def __init__(
86 self,
87 socket_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 socket_path = socket_url.replace("http+unix://", "")
93 if not socket_path.startswith("/"):
94 socket_path = "/" + socket_path
95 self.socket_path = socket_path
96 self.timeout = timeout
97 self.max_pool_size = max_pool_size
98
99 def f(p: t.Any) -> None:
100 p.close()
101
102 self.pools = RecentlyUsedContainer(pool_connections, dispose_func=f)
103 super().__init__()
104
105 def get_connection(
106 self, url: str | bytes, proxies: Mapping[str, str] | None = None
107 ) -> UnixHTTPConnectionPool:
108 with self.pools.lock:
109 pool = self.pools.get(url)
110 if pool:
111 return pool
112
113 pool = UnixHTTPConnectionPool(
114 url, self.socket_path, self.timeout, maxsize=self.max_pool_size
115 )
116 self.pools[url] = pool
117
118 return pool
119
120 def request_url(self, request: PreparedRequest, proxies: Mapping[str, str]) -> str:
121 # The select_proxy utility in requests errors out when the provided URL
122 # does not have a hostname, like is the case when using a UNIX socket.
123 # Since proxies are an irrelevant notion in the case of UNIX sockets
124 # anyway, we simply return the path URL directly.
125 # See also: https://github.com/docker/docker-py/issues/811
126 return request.path_url