| 1 |
"""Connection abstraction for interacting with test hosts.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import abc |
| 6 |
import shlex |
| 7 |
import tempfile |
| 8 |
import typing as t |
| 9 |
|
| 10 |
from .io import ( |
| 11 |
read_text_file, |
| 12 |
) |
| 13 |
|
| 14 |
from .config import ( |
| 15 |
EnvironmentConfig, |
| 16 |
) |
| 17 |
|
| 18 |
from .util import ( |
| 19 |
Display, |
| 20 |
OutputStream, |
| 21 |
SubprocessError, |
| 22 |
retry, |
| 23 |
) |
| 24 |
|
| 25 |
from .util_common import ( |
| 26 |
run_command, |
| 27 |
) |
| 28 |
|
| 29 |
from .docker_util import ( |
| 30 |
DockerInspect, |
| 31 |
docker_exec, |
| 32 |
docker_inspect, |
| 33 |
docker_network_disconnect, |
| 34 |
) |
| 35 |
|
| 36 |
from .ssh import ( |
| 37 |
SshConnectionDetail, |
| 38 |
ssh_options_to_list, |
| 39 |
) |
| 40 |
|
| 41 |
from .become import ( |
| 42 |
Become, |
| 43 |
) |
| 44 |
|
| 45 |
|
| 46 |
class Connection(metaclass=abc.ABCMeta): |
| 47 |
"""Base class for connecting to a host.""" |
| 48 |
|
| 49 |
@abc.abstractmethod |
| 50 |
def run( |
| 51 |
self, |
| 52 |
command: list[str], |
| 53 |
capture: bool, |
| 54 |
interactive: bool = False, |
| 55 |
data: t.Optional[str] = None, |
| 56 |
stdin: t.Optional[t.IO[bytes]] = None, |
| 57 |
stdout: t.Optional[t.IO[bytes]] = None, |
| 58 |
output_stream: t.Optional[OutputStream] = None, |
| 59 |
) -> tuple[t.Optional[str], t.Optional[str]]: |
| 60 |
"""Run the specified command and return the result.""" |
| 61 |
|
| 62 |
def extract_archive( |
| 63 |
self, |
| 64 |
chdir: str, |
| 65 |
src: t.IO[bytes], |
| 66 |
): |
| 67 |
"""Extract the given archive file stream in the specified directory.""" |
| 68 |
tar_cmd = ['tar', 'oxzf', '-', '-C', chdir] |
| 69 |
|
| 70 |
retry(lambda: self.run(tar_cmd, stdin=src, capture=True)) |
| 71 |
|
| 72 |
def create_archive( |
| 73 |
self, |
| 74 |
chdir: str, |
| 75 |
name: str, |
| 76 |
dst: t.IO[bytes], |
| 77 |
exclude: t.Optional[str] = None, |
| 78 |
): |
| 79 |
"""Create the specified archive file stream from the specified directory, including the given name and optionally excluding the given name.""" |
| 80 |
tar_cmd = ['tar', 'cf', '-', '-C', chdir] |
| 81 |
gzip_cmd = ['gzip'] |
| 82 |
|
| 83 |
if exclude: |
| 84 |
tar_cmd += ['--exclude', exclude] |
| 85 |
|
| 86 |
tar_cmd.append(name) |
| 87 |
|
| 88 |
# Using gzip to compress the archive allows this to work on all POSIX systems we support. |
| 89 |
commands = [tar_cmd, gzip_cmd] |
| 90 |
|
| 91 |
sh_cmd = ['sh', '-c', ' | '.join(shlex.join(command) for command in commands)] |
| 92 |
|
| 93 |
retry(lambda: self.run(sh_cmd, stdout=dst, capture=True)) |
| 94 |
|
| 95 |
|
| 96 |
class LocalConnection(Connection): |
| 97 |
"""Connect to localhost.""" |
| 98 |
|
| 99 |
def __init__(self, args: EnvironmentConfig) -> None: |
| 100 |
self.args = args |
| 101 |
|
| 102 |
def run( |
| 103 |
self, |
| 104 |
command: list[str], |
| 105 |
capture: bool, |
| 106 |
interactive: bool = False, |
| 107 |
data: t.Optional[str] = None, |
| 108 |
stdin: t.Optional[t.IO[bytes]] = None, |
| 109 |
stdout: t.Optional[t.IO[bytes]] = None, |
| 110 |
output_stream: t.Optional[OutputStream] = None, |
| 111 |
) -> tuple[t.Optional[str], t.Optional[str]]: |
| 112 |
"""Run the specified command and return the result.""" |
| 113 |
return run_command( |
| 114 |
args=self.args, |
| 115 |
cmd=command, |
| 116 |
capture=capture, |
| 117 |
data=data, |
| 118 |
stdin=stdin, |
| 119 |
stdout=stdout, |
| 120 |
interactive=interactive, |
| 121 |
output_stream=output_stream, |
| 122 |
) |
| 123 |
|
| 124 |
|
| 125 |
class SshConnection(Connection): |
| 126 |
"""Connect to a host using SSH.""" |
| 127 |
|
| 128 |
def __init__(self, args: EnvironmentConfig, settings: SshConnectionDetail, become: t.Optional[Become] = None) -> None: |
| 129 |
self.args = args |
| 130 |
self.settings = settings |
| 131 |
self.become = become |
| 132 |
|
| 133 |
self.options = ['-i', settings.identity_file] |
| 134 |
|
| 135 |
ssh_options: dict[str, t.Union[int, str]] = dict( |
| 136 |
BatchMode='yes', |
| 137 |
StrictHostKeyChecking='no', |
| 138 |
UserKnownHostsFile='/dev/null', |
| 139 |
ServerAliveInterval=15, |
| 140 |
ServerAliveCountMax=4, |
| 141 |
) |
| 142 |
|
| 143 |
ssh_options.update(settings.options) |
| 144 |
|
| 145 |
self.options.extend(ssh_options_to_list(ssh_options)) |
| 146 |
|
| 147 |
def run( |
| 148 |
self, |
| 149 |
command: list[str], |
| 150 |
capture: bool, |
| 151 |
interactive: bool = False, |
| 152 |
data: t.Optional[str] = None, |
| 153 |
stdin: t.Optional[t.IO[bytes]] = None, |
| 154 |
stdout: t.Optional[t.IO[bytes]] = None, |
| 155 |
output_stream: t.Optional[OutputStream] = None, |
| 156 |
) -> tuple[t.Optional[str], t.Optional[str]]: |
| 157 |
"""Run the specified command and return the result.""" |
| 158 |
options = list(self.options) |
| 159 |
|
| 160 |
if self.become: |
| 161 |
command = self.become.prepare_command(command) |
| 162 |
|
| 163 |
options.append('-q') |
| 164 |
|
| 165 |
if interactive: |
| 166 |
options.append('-tt') |
| 167 |
|
| 168 |
with tempfile.NamedTemporaryFile(prefix='ansible-test-ssh-debug-', suffix='.log') as ssh_logfile: |
| 169 |
options.extend(['-vvv', '-E', ssh_logfile.name]) |
| 170 |
|
| 171 |
if self.settings.port: |
| 172 |
options.extend(['-p', str(self.settings.port)]) |
| 173 |
|
| 174 |
options.append(f'{self.settings.user}@{self.settings.host}') |
| 175 |
options.append(shlex.join(command)) |
| 176 |
|
| 177 |
def error_callback(ex: SubprocessError) -> None: |
| 178 |
"""Error handler.""" |
| 179 |
self.capture_log_details(ssh_logfile.name, ex) |
| 180 |
|
| 181 |
return run_command( |
| 182 |
args=self.args, |
| 183 |
cmd=['ssh'] + options, |
| 184 |
capture=capture, |
| 185 |
data=data, |
| 186 |
stdin=stdin, |
| 187 |
stdout=stdout, |
| 188 |
interactive=interactive, |
| 189 |
output_stream=output_stream, |
| 190 |
error_callback=error_callback, |
| 191 |
) |
| 192 |
|
| 193 |
@staticmethod |
| 194 |
def capture_log_details(path: str, ex: SubprocessError) -> None: |
| 195 |
"""Read the specified SSH debug log and add relevant details to the provided exception.""" |
| 196 |
if ex.status != 255: |
| 197 |
return |
| 198 |
|
| 199 |
markers = [ |
| 200 |
'debug1: Connection Established', |
| 201 |
'debug1: Authentication successful', |
| 202 |
'debug1: Entering interactive session', |
| 203 |
'debug1: Sending command', |
| 204 |
'debug2: PTY allocation request accepted', |
| 205 |
'debug2: exec request accepted', |
| 206 |
] |
| 207 |
|
| 208 |
file_contents = read_text_file(path) |
| 209 |
messages = [] |
| 210 |
|
| 211 |
for line in reversed(file_contents.splitlines()): |
| 212 |
messages.append(line) |
| 213 |
|
| 214 |
if any(line.startswith(marker) for marker in markers): |
| 215 |
break |
| 216 |
|
| 217 |
message = '\n'.join(reversed(messages)) |
| 218 |
|
| 219 |
ex.message += '>>> SSH Debug Output\n' |
| 220 |
ex.message += '%s%s\n' % (message.strip(), Display.clear) |
| 221 |
|
| 222 |
|
| 223 |
class DockerConnection(Connection): |
| 224 |
"""Connect to a host using Docker.""" |
| 225 |
|
| 226 |
def __init__(self, args: EnvironmentConfig, container_id: str, user: t.Optional[str] = None) -> None: |
| 227 |
self.args = args |
| 228 |
self.container_id = container_id |
| 229 |
self.user: t.Optional[str] = user |
| 230 |
|
| 231 |
def run( |
| 232 |
self, |
| 233 |
command: list[str], |
| 234 |
capture: bool, |
| 235 |
interactive: bool = False, |
| 236 |
data: t.Optional[str] = None, |
| 237 |
stdin: t.Optional[t.IO[bytes]] = None, |
| 238 |
stdout: t.Optional[t.IO[bytes]] = None, |
| 239 |
output_stream: t.Optional[OutputStream] = None, |
| 240 |
) -> tuple[t.Optional[str], t.Optional[str]]: |
| 241 |
"""Run the specified command and return the result.""" |
| 242 |
options = [] |
| 243 |
|
| 244 |
if self.user: |
| 245 |
options.extend(['--user', self.user]) |
| 246 |
|
| 247 |
if interactive: |
| 248 |
options.append('-it') |
| 249 |
|
| 250 |
return docker_exec( |
| 251 |
args=self.args, |
| 252 |
container_id=self.container_id, |
| 253 |
cmd=command, |
| 254 |
options=options, |
| 255 |
capture=capture, |
| 256 |
data=data, |
| 257 |
stdin=stdin, |
| 258 |
stdout=stdout, |
| 259 |
interactive=interactive, |
| 260 |
output_stream=output_stream, |
| 261 |
) |
| 262 |
|
| 263 |
def inspect(self) -> DockerInspect: |
| 264 |
"""Inspect the container and return a DockerInspect instance with the results.""" |
| 265 |
return docker_inspect(self.args, self.container_id) |
| 266 |
|
| 267 |
def disconnect_network(self, network: str) -> None: |
| 268 |
"""Disconnect the container from the specified network.""" |
| 269 |
docker_network_disconnect(self.args, self.container_id, network) |