| 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 logging |
| 15 |
import os |
| 16 |
import signal |
| 17 |
import socket |
| 18 |
import subprocess |
| 19 |
import traceback |
| 20 |
import typing as t |
| 21 |
from queue import Empty |
| 22 |
from urllib.parse import urlparse |
| 23 |
|
| 24 |
from .. import constants |
| 25 |
from .._import_helper import HTTPAdapter, urllib3, urllib3_connection |
| 26 |
from .basehttpadapter import BaseHTTPAdapter |
| 27 |
|
| 28 |
PARAMIKO_IMPORT_ERROR: str | None # pylint: disable=invalid-name |
| 29 |
try: |
| 30 |
import paramiko |
| 31 |
except ImportError: |
| 32 |
PARAMIKO_IMPORT_ERROR = traceback.format_exc() # pylint: disable=invalid-name |
| 33 |
else: |
| 34 |
PARAMIKO_IMPORT_ERROR = None # pylint: disable=invalid-name |
| 35 |
|
| 36 |
if t.TYPE_CHECKING: |
| 37 |
from collections.abc import Buffer, Mapping |
| 38 |
|
| 39 |
|
| 40 |
RecentlyUsedContainer = urllib3._collections.RecentlyUsedContainer |
| 41 |
|
| 42 |
|
| 43 |
class SSHSocket(socket.socket): |
| 44 |
def __init__(self, host: str) -> None: |
| 45 |
super().__init__(socket.AF_INET, socket.SOCK_STREAM) |
| 46 |
self.host = host |
| 47 |
self.port = None |
| 48 |
self.user = None |
| 49 |
if ":" in self.host: |
| 50 |
self.host, self.port = self.host.split(":") |
| 51 |
if "@" in self.host: |
| 52 |
self.user, self.host = self.host.split("@") |
| 53 |
|
| 54 |
self.proc: subprocess.Popen | None = None |
| 55 |
|
| 56 |
def connect(self, *args_: t.Any, **kwargs: t.Any) -> None: |
| 57 |
args = ["ssh"] |
| 58 |
if self.user: |
| 59 |
args = args + ["-l", self.user] |
| 60 |
|
| 61 |
if self.port: |
| 62 |
args = args + ["-p", self.port] |
| 63 |
|
| 64 |
args = args + ["--", self.host, "docker system dial-stdio"] |
| 65 |
|
| 66 |
preexec_func = None |
| 67 |
if not constants.IS_WINDOWS_PLATFORM: |
| 68 |
|
| 69 |
def f() -> None: |
| 70 |
signal.signal(signal.SIGINT, signal.SIG_IGN) |
| 71 |
|
| 72 |
preexec_func = f |
| 73 |
|
| 74 |
env = dict(os.environ) |
| 75 |
|
| 76 |
# drop LD_LIBRARY_PATH and SSL_CERT_FILE |
| 77 |
env.pop("LD_LIBRARY_PATH", None) |
| 78 |
env.pop("SSL_CERT_FILE", None) |
| 79 |
|
| 80 |
self.proc = subprocess.Popen( # pylint: disable=consider-using-with |
| 81 |
args, |
| 82 |
env=env, |
| 83 |
stdout=subprocess.PIPE, |
| 84 |
stdin=subprocess.PIPE, |
| 85 |
preexec_fn=preexec_func, |
| 86 |
) |
| 87 |
|
| 88 |
def _write(self, data: Buffer) -> int: |
| 89 |
if not self.proc: |
| 90 |
raise RuntimeError( |
| 91 |
"SSH subprocess not initiated. connect() must be called first." |
| 92 |
) |
| 93 |
assert self.proc.stdin is not None |
| 94 |
if self.proc.stdin.closed: |
| 95 |
raise RuntimeError( |
| 96 |
"SSH subprocess not initiated. connect() must be called first after close()." |
| 97 |
) |
| 98 |
written = self.proc.stdin.write(data) |
| 99 |
self.proc.stdin.flush() |
| 100 |
return written |
| 101 |
|
| 102 |
def sendall(self, data: Buffer, *args: t.Any, **kwargs: t.Any) -> None: |
| 103 |
self._write(data) |
| 104 |
|
| 105 |
def send(self, data: Buffer, *args: t.Any, **kwargs: t.Any) -> int: |
| 106 |
return self._write(data) |
| 107 |
|
| 108 |
def recv(self, n: int, *args: t.Any, **kwargs: t.Any) -> bytes: |
| 109 |
if not self.proc: |
| 110 |
raise RuntimeError( |
| 111 |
"SSH subprocess not initiated. connect() must be called first." |
| 112 |
) |
| 113 |
assert self.proc.stdout is not None |
| 114 |
return self.proc.stdout.read(n) |
| 115 |
|
| 116 |
def makefile(self, mode: str, *args: t.Any, **kwargs: t.Any) -> t.IO: # type: ignore |
| 117 |
if not self.proc: |
| 118 |
self.connect() |
| 119 |
assert self.proc is not None |
| 120 |
assert self.proc.stdout is not None |
| 121 |
self.proc.stdout.channel = self # type: ignore |
| 122 |
|
| 123 |
return self.proc.stdout |
| 124 |
|
| 125 |
def close(self) -> None: |
| 126 |
if not self.proc: |
| 127 |
return |
| 128 |
assert self.proc.stdin is not None |
| 129 |
if self.proc.stdin.closed: |
| 130 |
return |
| 131 |
self.proc.stdin.write(b"\n\n") |
| 132 |
self.proc.stdin.flush() |
| 133 |
self.proc.terminate() |
| 134 |
|
| 135 |
|
| 136 |
class SSHConnection(urllib3_connection.HTTPConnection): |
| 137 |
def __init__( |
| 138 |
self, |
| 139 |
*, |
| 140 |
ssh_transport: paramiko.Transport | None = None, |
| 141 |
timeout: int | float = 60, |
| 142 |
host: str, |
| 143 |
) -> None: |
| 144 |
super().__init__("localhost", timeout=timeout) |
| 145 |
self.ssh_transport = ssh_transport |
| 146 |
self.timeout = timeout |
| 147 |
self.ssh_host = host |
| 148 |
self.sock: paramiko.Channel | SSHSocket | None = None |
| 149 |
|
| 150 |
def connect(self) -> None: |
| 151 |
if self.ssh_transport: |
| 152 |
channel = self.ssh_transport.open_session() |
| 153 |
channel.settimeout(self.timeout) |
| 154 |
channel.exec_command("docker system dial-stdio") |
| 155 |
self.sock = channel |
| 156 |
else: |
| 157 |
sock = SSHSocket(self.ssh_host) |
| 158 |
sock.settimeout(self.timeout) |
| 159 |
sock.connect() |
| 160 |
self.sock = sock |
| 161 |
|
| 162 |
|
| 163 |
class SSHConnectionPool(urllib3.connectionpool.HTTPConnectionPool): |
| 164 |
scheme = "ssh" |
| 165 |
|
| 166 |
def __init__( |
| 167 |
self, |
| 168 |
*, |
| 169 |
ssh_client: paramiko.SSHClient | None = None, |
| 170 |
timeout: int | float = 60, |
| 171 |
maxsize: int = 10, |
| 172 |
host: str, |
| 173 |
) -> None: |
| 174 |
super().__init__("localhost", timeout=timeout, maxsize=maxsize) |
| 175 |
self.ssh_transport: paramiko.Transport | None = None |
| 176 |
self.timeout = timeout |
| 177 |
if ssh_client: |
| 178 |
self.ssh_transport = ssh_client.get_transport() |
| 179 |
self.ssh_host = host |
| 180 |
|
| 181 |
def _new_conn(self) -> SSHConnection: |
| 182 |
return SSHConnection( |
| 183 |
ssh_transport=self.ssh_transport, |
| 184 |
timeout=self.timeout, |
| 185 |
host=self.ssh_host, |
| 186 |
) |
| 187 |
|
| 188 |
# When re-using connections, urllib3 calls fileno() on our |
| 189 |
# SSH channel instance, quickly overloading our fd limit. To avoid this, |
| 190 |
# we override _get_conn |
| 191 |
def _get_conn(self, timeout: int | float) -> SSHConnection: |
| 192 |
conn = None |
| 193 |
try: |
| 194 |
conn = self.pool.get(block=self.block, timeout=timeout) |
| 195 |
|
| 196 |
except AttributeError as exc: # self.pool is None |
| 197 |
raise urllib3.exceptions.ClosedPoolError(self, "Pool is closed.") from exc |
| 198 |
|
| 199 |
except Empty as exc: |
| 200 |
if self.block: |
| 201 |
raise urllib3.exceptions.EmptyPoolError( |
| 202 |
self, |
| 203 |
"Pool reached maximum size and no more connections are allowed.", |
| 204 |
) from exc |
| 205 |
# Oh well, we'll create a new connection then |
| 206 |
|
| 207 |
return conn or self._new_conn() |
| 208 |
|
| 209 |
|
| 210 |
class SSHHTTPAdapter(BaseHTTPAdapter): |
| 211 |
__attrs__ = HTTPAdapter.__attrs__ + [ |
| 212 |
"pools", |
| 213 |
"timeout", |
| 214 |
"ssh_client", |
| 215 |
"ssh_params", |
| 216 |
"max_pool_size", |
| 217 |
] |
| 218 |
|
| 219 |
def __init__( |
| 220 |
self, |
| 221 |
base_url: str, |
| 222 |
timeout: int | float = 60, |
| 223 |
pool_connections: int = constants.DEFAULT_NUM_POOLS, |
| 224 |
max_pool_size: int = constants.DEFAULT_MAX_POOL_SIZE, |
| 225 |
shell_out: bool = False, |
| 226 |
) -> None: |
| 227 |
self.ssh_client: paramiko.SSHClient | None = None |
| 228 |
if not shell_out: |
| 229 |
self._create_paramiko_client(base_url) |
| 230 |
self._connect() |
| 231 |
|
| 232 |
self.ssh_host = base_url |
| 233 |
if base_url.startswith("ssh://"): |
| 234 |
self.ssh_host = base_url[len("ssh://") :] |
| 235 |
|
| 236 |
self.timeout = timeout |
| 237 |
self.max_pool_size = max_pool_size |
| 238 |
self.pools = RecentlyUsedContainer( |
| 239 |
pool_connections, dispose_func=lambda p: p.close() |
| 240 |
) |
| 241 |
super().__init__() |
| 242 |
|
| 243 |
def _create_paramiko_client(self, base_url: str) -> None: |
| 244 |
logging.getLogger("paramiko").setLevel(logging.WARNING) |
| 245 |
self.ssh_client = paramiko.SSHClient() |
| 246 |
base_url_p = urlparse(base_url) |
| 247 |
assert base_url_p.hostname is not None |
| 248 |
self.ssh_params: dict[str, t.Any] = { |
| 249 |
"hostname": base_url_p.hostname, |
| 250 |
"port": base_url_p.port, |
| 251 |
"username": base_url_p.username, |
| 252 |
} |
| 253 |
ssh_config_file = os.path.expanduser("~/.ssh/config") |
| 254 |
if os.path.exists(ssh_config_file): |
| 255 |
conf = paramiko.SSHConfig() |
| 256 |
with open(ssh_config_file, "rt", encoding="utf-8") as f: |
| 257 |
conf.parse(f) |
| 258 |
host_config = conf.lookup(base_url_p.hostname) |
| 259 |
if "proxycommand" in host_config: |
| 260 |
self.ssh_params["sock"] = paramiko.ProxyCommand( |
| 261 |
host_config["proxycommand"] |
| 262 |
) |
| 263 |
if "hostname" in host_config: |
| 264 |
self.ssh_params["hostname"] = host_config["hostname"] |
| 265 |
if base_url_p.port is None and "port" in host_config: |
| 266 |
self.ssh_params["port"] = host_config["port"] |
| 267 |
if base_url_p.username is None and "user" in host_config: |
| 268 |
self.ssh_params["username"] = host_config["user"] |
| 269 |
if "identityfile" in host_config: |
| 270 |
self.ssh_params["key_filename"] = host_config["identityfile"] |
| 271 |
|
| 272 |
self.ssh_client.load_system_host_keys() |
| 273 |
self.ssh_client.set_missing_host_key_policy(paramiko.RejectPolicy()) |
| 274 |
|
| 275 |
def _connect(self) -> None: |
| 276 |
if self.ssh_client: |
| 277 |
self.ssh_client.connect(**self.ssh_params) |
| 278 |
|
| 279 |
def get_connection( |
| 280 |
self, url: str | bytes, proxies: Mapping[str, str] | None = None |
| 281 |
) -> SSHConnectionPool: |
| 282 |
if not self.ssh_client: |
| 283 |
return SSHConnectionPool( |
| 284 |
ssh_client=self.ssh_client, |
| 285 |
timeout=self.timeout, |
| 286 |
maxsize=self.max_pool_size, |
| 287 |
host=self.ssh_host, |
| 288 |
) |
| 289 |
with self.pools.lock: |
| 290 |
pool = self.pools.get(url) |
| 291 |
if pool: |
| 292 |
return pool |
| 293 |
|
| 294 |
# Connection is closed try a reconnect |
| 295 |
if self.ssh_client and not self.ssh_client.get_transport(): |
| 296 |
self._connect() |
| 297 |
|
| 298 |
pool = SSHConnectionPool( |
| 299 |
ssh_client=self.ssh_client, |
| 300 |
timeout=self.timeout, |
| 301 |
maxsize=self.max_pool_size, |
| 302 |
host=self.ssh_host, |
| 303 |
) |
| 304 |
self.pools[url] = pool |
| 305 |
|
| 306 |
return pool |
| 307 |
|
| 308 |
def close(self) -> None: |
| 309 |
super().close() |
| 310 |
if self.ssh_client: |
| 311 |
self.ssh_client.close() |