| 1 |
"""Profiles to represent individual test hosts or a user-provided inventory file.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import abc |
| 6 |
import base64 |
| 7 |
import dataclasses |
| 8 |
import json |
| 9 |
import os |
| 10 |
import pathlib |
| 11 |
import shlex |
| 12 |
import tempfile |
| 13 |
import time |
| 14 |
import typing as t |
| 15 |
|
| 16 |
from .io import ( |
| 17 |
read_text_file, |
| 18 |
write_text_file, |
| 19 |
) |
| 20 |
|
| 21 |
from .config import ( |
| 22 |
CommonConfig, |
| 23 |
EnvironmentConfig, |
| 24 |
IntegrationConfig, |
| 25 |
TerminateMode, |
| 26 |
) |
| 27 |
|
| 28 |
from .host_configs import ( |
| 29 |
ControllerConfig, |
| 30 |
ControllerHostConfig, |
| 31 |
DockerConfig, |
| 32 |
HostConfig, |
| 33 |
NetworkInventoryConfig, |
| 34 |
NetworkRemoteConfig, |
| 35 |
OriginConfig, |
| 36 |
PosixConfig, |
| 37 |
PosixRemoteConfig, |
| 38 |
PosixSshConfig, |
| 39 |
PythonConfig, |
| 40 |
RemoteConfig, |
| 41 |
VirtualPythonConfig, |
| 42 |
WindowsInventoryConfig, |
| 43 |
WindowsRemoteConfig, |
| 44 |
PowerShellConfig, |
| 45 |
) |
| 46 |
|
| 47 |
from .core_ci import ( |
| 48 |
AnsibleCoreCI, |
| 49 |
SshKey, |
| 50 |
VmResource, |
| 51 |
) |
| 52 |
|
| 53 |
from .util import ( |
| 54 |
ApplicationError, |
| 55 |
SubprocessError, |
| 56 |
cache, |
| 57 |
display, |
| 58 |
get_type_map, |
| 59 |
sanitize_host_name, |
| 60 |
sorted_versions, |
| 61 |
InternalError, |
| 62 |
HostConnectionError, |
| 63 |
ANSIBLE_TEST_TARGET_ROOT, |
| 64 |
WINDOWS_CONNECTION_VARIABLES, |
| 65 |
ANSIBLE_SOURCE_ROOT, |
| 66 |
ANSIBLE_LIB_ROOT, |
| 67 |
ANSIBLE_TEST_ROOT, |
| 68 |
Architecture, |
| 69 |
get_powershell_version_map, |
| 70 |
) |
| 71 |
|
| 72 |
from .util_common import ( |
| 73 |
get_docs_url, |
| 74 |
intercept_python, |
| 75 |
) |
| 76 |
|
| 77 |
from .docker_util import ( |
| 78 |
docker_exec, |
| 79 |
docker_image_inspect, |
| 80 |
docker_logs, |
| 81 |
docker_pull, |
| 82 |
docker_rm, |
| 83 |
get_docker_hostname, |
| 84 |
require_docker, |
| 85 |
get_docker_info, |
| 86 |
detect_host_properties, |
| 87 |
run_utility_container, |
| 88 |
SystemdControlGroupV1Status, |
| 89 |
LOGINUID_NOT_SET, |
| 90 |
UTILITY_IMAGE, |
| 91 |
) |
| 92 |
|
| 93 |
from .bootstrap import ( |
| 94 |
BootstrapDocker, |
| 95 |
BootstrapRemote, |
| 96 |
) |
| 97 |
|
| 98 |
from .venv import ( |
| 99 |
get_virtual_python, |
| 100 |
) |
| 101 |
|
| 102 |
from .ssh import ( |
| 103 |
SshConnectionDetail, |
| 104 |
create_ssh_port_forwards, |
| 105 |
SshProcess, |
| 106 |
) |
| 107 |
|
| 108 |
from .ansible_util import ( |
| 109 |
ansible_environment, |
| 110 |
get_hosts, |
| 111 |
parse_inventory, |
| 112 |
) |
| 113 |
|
| 114 |
from .containers import ( |
| 115 |
HostType, |
| 116 |
get_container_database, |
| 117 |
run_support_container, |
| 118 |
) |
| 119 |
|
| 120 |
from .connections import ( |
| 121 |
Connection, |
| 122 |
DockerConnection, |
| 123 |
LocalConnection, |
| 124 |
SshConnection, |
| 125 |
) |
| 126 |
|
| 127 |
from .become import ( |
| 128 |
Become, |
| 129 |
SUPPORTED_BECOME_METHODS, |
| 130 |
Sudo, |
| 131 |
) |
| 132 |
|
| 133 |
from .completion import ( |
| 134 |
AuditMode, |
| 135 |
CGroupVersion, |
| 136 |
) |
| 137 |
|
| 138 |
from .dev.container_probe import ( |
| 139 |
CGroupMount, |
| 140 |
CGroupPath, |
| 141 |
CGroupState, |
| 142 |
MountType, |
| 143 |
check_container_cgroup_status, |
| 144 |
) |
| 145 |
|
| 146 |
from .debugging import ( |
| 147 |
DebuggerProfile, |
| 148 |
DebuggerSettings, |
| 149 |
) |
| 150 |
|
| 151 |
|
| 152 |
class ControlGroupError(ApplicationError): |
| 153 |
"""Raised when the container host does not have the necessary cgroup support to run a container.""" |
| 154 |
|
| 155 |
def __init__(self, args: CommonConfig, reason: str) -> None: |
| 156 |
engine = require_docker().command |
| 157 |
dd_wsl2 = get_docker_info(args).docker_desktop_wsl2 |
| 158 |
|
| 159 |
message = f''' |
| 160 |
{reason} |
| 161 |
|
| 162 |
Run the following commands as root on the container host to resolve this issue: |
| 163 |
|
| 164 |
mkdir /sys/fs/cgroup/systemd |
| 165 |
mount cgroup -t cgroup /sys/fs/cgroup/systemd -o none,name=systemd,xattr |
| 166 |
chown -R {{user}}:{{group}} /sys/fs/cgroup/systemd # only when rootless |
| 167 |
|
| 168 |
NOTE: These changes must be applied each time the container host is rebooted. |
| 169 |
'''.strip() |
| 170 |
|
| 171 |
podman_message = ''' |
| 172 |
If rootless Podman is already running [1], you may need to stop it before |
| 173 |
containers are able to use the new mount point. |
| 174 |
|
| 175 |
[1] Check for 'podman' and 'catatonit' processes. |
| 176 |
''' |
| 177 |
|
| 178 |
dd_wsl_message = f''' |
| 179 |
When using Docker Desktop with WSL2, additional configuration [1] is required. |
| 180 |
|
| 181 |
[1] {get_docs_url("https://docs.ansible.com/ansible-core/devel/dev_guide/testing_running_locally.html#docker-desktop-with-wsl2")} |
| 182 |
''' |
| 183 |
|
| 184 |
if engine == 'podman': |
| 185 |
message += podman_message |
| 186 |
elif dd_wsl2: |
| 187 |
message += dd_wsl_message |
| 188 |
|
| 189 |
message = message.strip() |
| 190 |
|
| 191 |
super().__init__(message) |
| 192 |
|
| 193 |
|
| 194 |
@dataclasses.dataclass(frozen=True) |
| 195 |
class Inventory: |
| 196 |
"""Simple representation of an Ansible inventory.""" |
| 197 |
|
| 198 |
host_groups: dict[str, dict[str, dict[str, t.Union[str, int]]]] |
| 199 |
extra_groups: t.Optional[dict[str, list[str]]] = None |
| 200 |
|
| 201 |
@staticmethod |
| 202 |
def create_single_host(name: str, variables: dict[str, t.Union[str, int]]) -> Inventory: |
| 203 |
"""Return an inventory instance created from the given hostname and variables.""" |
| 204 |
return Inventory(host_groups=dict(all={name: variables})) |
| 205 |
|
| 206 |
def write(self, args: CommonConfig, path: str) -> None: |
| 207 |
"""Write the given inventory to the specified path on disk.""" |
| 208 |
|
| 209 |
inventory_data: dict[str, dict[str, dict[str, dict[str, object]]]] = dict() |
| 210 |
|
| 211 |
for group, hosts in self.host_groups.items(): |
| 212 |
group_data = inventory_data.setdefault(group, dict()) |
| 213 |
hosts_data = group_data.setdefault('hosts', dict()) |
| 214 |
|
| 215 |
for host, variables in hosts.items(): |
| 216 |
host_entry = hosts_data.setdefault(host, dict()) |
| 217 |
host_entry.update(variables) |
| 218 |
|
| 219 |
for group, children in (self.extra_groups or {}).items(): |
| 220 |
group_data = inventory_data.setdefault(group, dict()) |
| 221 |
group_children = group_data.setdefault('children', dict()) |
| 222 |
|
| 223 |
for child in children: |
| 224 |
group_children[child] = dict() |
| 225 |
|
| 226 |
inventory_text = json.dumps(inventory_data, indent=4) |
| 227 |
|
| 228 |
if not args.explain: |
| 229 |
write_text_file(path, inventory_text + '\n') |
| 230 |
|
| 231 |
display.info(f'>>> Inventory\n{inventory_text}', verbosity=3) |
| 232 |
|
| 233 |
|
| 234 |
class HostProfile[THostConfig: HostConfig](metaclass=abc.ABCMeta): |
| 235 |
"""Base class for host profiles.""" |
| 236 |
|
| 237 |
def __init__( |
| 238 |
self, |
| 239 |
*, |
| 240 |
args: EnvironmentConfig, |
| 241 |
config: THostConfig, |
| 242 |
controller: ControllerHostProfile, |
| 243 |
) -> None: |
| 244 |
self.args = args |
| 245 |
self.config = config |
| 246 |
self.controller = not controller # this profile is a controller whenever the `controller` arg was not provided |
| 247 |
self.targets = args.targets if self.controller else [] # only keep targets if this profile is a controller |
| 248 |
self.controller_profile = controller if isinstance(self, ControllerProfile) else None |
| 249 |
|
| 250 |
self.state: dict[str, t.Any] = {} |
| 251 |
"""State that must be persisted across delegation.""" |
| 252 |
self.cache: dict[str, t.Any] = {} |
| 253 |
"""Cache that must not be persisted across delegation.""" |
| 254 |
|
| 255 |
@property |
| 256 |
@abc.abstractmethod |
| 257 |
def name(self) -> str: |
| 258 |
"""The name of the host profile.""" |
| 259 |
|
| 260 |
def pre_provision(self) -> None: |
| 261 |
"""Pre-provision the host profile.""" |
| 262 |
|
| 263 |
def provision(self) -> None: |
| 264 |
"""Provision the host before delegation.""" |
| 265 |
|
| 266 |
def setup(self) -> None: |
| 267 |
"""Perform out-of-band setup before delegation.""" |
| 268 |
|
| 269 |
def on_target_failure(self) -> None: |
| 270 |
"""Executed during failure handling if this profile is a target.""" |
| 271 |
|
| 272 |
def deprovision(self) -> None: |
| 273 |
"""Deprovision the host after delegation has completed.""" |
| 274 |
|
| 275 |
def wait(self) -> None: |
| 276 |
"""Wait for the instance to be ready. Executed before delegation for the controller and after delegation for targets.""" |
| 277 |
|
| 278 |
def configure(self) -> None: |
| 279 |
"""Perform in-band configuration. Executed before delegation for the controller and after delegation for targets.""" |
| 280 |
|
| 281 |
def __getstate__(self): |
| 282 |
return {key: value for key, value in self.__dict__.items() if key not in ('args', 'cache')} |
| 283 |
|
| 284 |
def __setstate__(self, state): |
| 285 |
self.__dict__.update(state) |
| 286 |
|
| 287 |
# args will be populated after the instances are restored |
| 288 |
self.cache = {} |
| 289 |
|
| 290 |
def __str__(self) -> str: |
| 291 |
return f'{self.__class__.__name__}: {self.name}' |
| 292 |
|
| 293 |
|
| 294 |
class DebuggableProfile[THostConfig: HostConfig](HostProfile[THostConfig], DebuggerProfile, metaclass=abc.ABCMeta): |
| 295 |
"""Base class for profiles remote debugging.""" |
| 296 |
|
| 297 |
__DEBUGGING_PORT_KEY = 'debugging_port' |
| 298 |
__DEBUGGING_FORWARDER_KEY = 'debugging_forwarder' |
| 299 |
|
| 300 |
@property |
| 301 |
def debugger(self) -> DebuggerSettings | None: |
| 302 |
"""The debugger settings for this host if present and enabled, otherwise None.""" |
| 303 |
return self.args.metadata.debugger_settings |
| 304 |
|
| 305 |
@property |
| 306 |
def debugging_enabled(self) -> bool: |
| 307 |
"""Returns `True` if debugging is enabled for this profile, otherwise `False`.""" |
| 308 |
if self.controller: |
| 309 |
return self.args.metadata.debugger_flags.enable |
| 310 |
|
| 311 |
return self.args.metadata.debugger_flags.ansiballz |
| 312 |
|
| 313 |
@property |
| 314 |
def debugger_host(self) -> str: |
| 315 |
"""The debugger host to use.""" |
| 316 |
return 'localhost' |
| 317 |
|
| 318 |
@property |
| 319 |
def debugger_port(self) -> int: |
| 320 |
"""The debugger port to use.""" |
| 321 |
return self.state.get(self.__DEBUGGING_PORT_KEY) or self.origin_debugger_port |
| 322 |
|
| 323 |
@property |
| 324 |
def debugging_forwarder(self) -> SshProcess | None: |
| 325 |
"""The SSH forwarding process, if enabled.""" |
| 326 |
return self.cache.get(self.__DEBUGGING_FORWARDER_KEY) |
| 327 |
|
| 328 |
@debugging_forwarder.setter |
| 329 |
def debugging_forwarder(self, value: SshProcess) -> None: |
| 330 |
"""The SSH forwarding process, if enabled.""" |
| 331 |
self.cache[self.__DEBUGGING_FORWARDER_KEY] = value |
| 332 |
|
| 333 |
@property |
| 334 |
def origin_debugger_port(self) -> int: |
| 335 |
"""The debugger port on the origin.""" |
| 336 |
return self.debugger.port |
| 337 |
|
| 338 |
def enable_debugger_forwarding(self, ssh: SshConnectionDetail) -> None: |
| 339 |
"""Enable debugger port forwarding from the origin.""" |
| 340 |
if not self.debugging_enabled: |
| 341 |
return |
| 342 |
|
| 343 |
endpoint = ('localhost', self.origin_debugger_port) |
| 344 |
forwards = [endpoint] |
| 345 |
|
| 346 |
self.debugging_forwarder = create_ssh_port_forwards(self.args, ssh, forwards) |
| 347 |
|
| 348 |
port_forwards = self.debugging_forwarder.collect_port_forwards() |
| 349 |
|
| 350 |
self.state[self.__DEBUGGING_PORT_KEY] = port = port_forwards[endpoint] |
| 351 |
|
| 352 |
display.info(f'Remote debugging of {self.name!r} is available on port {port}.', verbosity=1) |
| 353 |
|
| 354 |
def deprovision(self) -> None: |
| 355 |
"""Deprovision the host after delegation has completed.""" |
| 356 |
super().deprovision() |
| 357 |
|
| 358 |
if not self.debugging_forwarder: |
| 359 |
return # forwarding not in use |
| 360 |
|
| 361 |
self.debugging_forwarder.terminate() |
| 362 |
|
| 363 |
display.info(f'Waiting for the {self.name!r} remote debugging SSH port forwarding process to terminate.', verbosity=1) |
| 364 |
|
| 365 |
self.debugging_forwarder.wait() |
| 366 |
|
| 367 |
def get_source_mapping(self) -> dict[str, str]: |
| 368 |
"""Get the source mapping from the given metadata.""" |
| 369 |
from . import data_context |
| 370 |
|
| 371 |
if collection := data_context().content.collection: |
| 372 |
source_mapping = { |
| 373 |
f"{self.args.metadata.ansible_test_root}/": f'{ANSIBLE_TEST_ROOT}/', |
| 374 |
f"{self.args.metadata.ansible_lib_root}/": f'{ANSIBLE_LIB_ROOT}/', |
| 375 |
f'{self.args.metadata.collection_root}/ansible_collections/': f'{collection.root}/ansible_collections/', |
| 376 |
} |
| 377 |
else: |
| 378 |
ansible_source_root = pathlib.Path(self.args.metadata.ansible_lib_root).parent.parent |
| 379 |
|
| 380 |
source_mapping = { |
| 381 |
f"{ansible_source_root}/": f'{ANSIBLE_SOURCE_ROOT}/', |
| 382 |
} |
| 383 |
|
| 384 |
source_mapping = {key: value for key, value in source_mapping.items() if key != value} |
| 385 |
|
| 386 |
return source_mapping |
| 387 |
|
| 388 |
def activate_debugger(self) -> None: |
| 389 |
"""Activate the debugger after delegation.""" |
| 390 |
if not self.args.metadata.loaded or not self.args.metadata.debugger_flags.self: |
| 391 |
return |
| 392 |
|
| 393 |
display.info('Activating remote debugging of ansible-test.', verbosity=1) |
| 394 |
|
| 395 |
os.environ.update(self.debugger.get_environment_variables(self)) |
| 396 |
|
| 397 |
self.debugger.activate_debugger(self) |
| 398 |
|
| 399 |
pass # pylint: disable=unnecessary-pass # when suspend is True, execution pauses here -- it's also a convenient place to put a breakpoint |
| 400 |
|
| 401 |
def get_ansiballz_inventory_variables(self) -> dict[str, t.Any]: |
| 402 |
""" |
| 403 |
Return inventory variables for remote debugging of AnsiballZ modules. |
| 404 |
When delegating, this function must be called after delegation. |
| 405 |
""" |
| 406 |
if not self.args.metadata.debugger_flags.ansiballz: |
| 407 |
return {} |
| 408 |
|
| 409 |
debug_type = self.debugger.get_debug_type() |
| 410 |
|
| 411 |
return { |
| 412 |
f"_ansible_ansiballz_{debug_type}_config": json.dumps(self.get_ansiballz_debugger_config()), |
| 413 |
} |
| 414 |
|
| 415 |
def get_ansiballz_environment_variables(self) -> dict[str, t.Any]: |
| 416 |
""" |
| 417 |
Return environment variables for remote debugging of AnsiballZ modules. |
| 418 |
When delegating, this function must be called after delegation. |
| 419 |
""" |
| 420 |
if not self.args.metadata.debugger_flags.ansiballz: |
| 421 |
return {} |
| 422 |
|
| 423 |
debug_type = self.debugger.get_debug_type().upper() |
| 424 |
|
| 425 |
return { |
| 426 |
f"_ANSIBLE_ANSIBALLZ_{debug_type}_CONFIG": json.dumps(self.get_ansiballz_debugger_config()), |
| 427 |
} |
| 428 |
|
| 429 |
def get_ansiballz_debugger_config(self) -> dict[str, t.Any]: |
| 430 |
""" |
| 431 |
Return config for remote debugging of AnsiballZ modules. |
| 432 |
When delegating, this function must be called after delegation. |
| 433 |
""" |
| 434 |
debugger_config = self.debugger.get_ansiballz_config(self) |
| 435 |
|
| 436 |
display.info(f'>>> Debugger Config ({self.name} AnsiballZ)\n{json.dumps(debugger_config, indent=4)}', verbosity=3) |
| 437 |
|
| 438 |
return debugger_config |
| 439 |
|
| 440 |
def get_ansible_cli_environment_variables(self) -> dict[str, t.Any]: |
| 441 |
""" |
| 442 |
Return environment variables for remote debugging of the Ansible CLI. |
| 443 |
When delegating, this function must be called after delegation. |
| 444 |
""" |
| 445 |
if not self.args.metadata.debugger_flags.cli: |
| 446 |
return {} |
| 447 |
|
| 448 |
debugger_config = dict( |
| 449 |
args=self.debugger.get_cli_arguments(self), |
| 450 |
env=self.debugger.get_environment_variables(self), |
| 451 |
) |
| 452 |
|
| 453 |
display.info(f'>>> Debugger Config ({self.name} Ansible CLI)\n{json.dumps(debugger_config, indent=4)}', verbosity=3) |
| 454 |
|
| 455 |
return dict( |
| 456 |
ANSIBLE_TEST_DEBUGGER_CONFIG=json.dumps(debugger_config), |
| 457 |
) |
| 458 |
|
| 459 |
|
| 460 |
class PosixProfile[TPosixConfig: PosixConfig](HostProfile[TPosixConfig], metaclass=abc.ABCMeta): |
| 461 |
"""Base class for POSIX host profiles.""" |
| 462 |
|
| 463 |
@property |
| 464 |
def python(self) -> PythonConfig: |
| 465 |
""" |
| 466 |
The Python to use for this profile. |
| 467 |
If it is a virtual python, it will be created the first time it is requested. |
| 468 |
""" |
| 469 |
python = self.state.get('python') |
| 470 |
|
| 471 |
if not python: |
| 472 |
python = self.config.python |
| 473 |
|
| 474 |
if isinstance(python, VirtualPythonConfig): |
| 475 |
python = get_virtual_python(self.args, python) |
| 476 |
|
| 477 |
self.state['python'] = python |
| 478 |
|
| 479 |
return python |
| 480 |
|
| 481 |
@property |
| 482 |
def powershell(self) -> PowerShellConfig: |
| 483 |
""" |
| 484 |
The PowerShell to use for this profile. |
| 485 |
""" |
| 486 |
powershell = self.state.get('powershell') |
| 487 |
|
| 488 |
if not powershell: |
| 489 |
powershell = self.config.powershell |
| 490 |
|
| 491 |
self.state['powershell'] = powershell |
| 492 |
|
| 493 |
return powershell |
| 494 |
|
| 495 |
def get_python_interpreters(self) -> dict[str, str]: |
| 496 |
""" |
| 497 |
Get a mapping of Python interpreter versions and paths to use. |
| 498 |
A target uses a single Python version, but a controller may include additional versions for targets running on the controller. |
| 499 |
""" |
| 500 |
python_interpreters = {self.python.version: self.python.path} |
| 501 |
python_interpreters.update({target.python.version: target.python.path for target in self.targets if isinstance(target, ControllerConfig)}) |
| 502 |
python_interpreters = {version: python_interpreters[version] for version in sorted_versions(list(python_interpreters))} |
| 503 |
|
| 504 |
return python_interpreters |
| 505 |
|
| 506 |
def get_powershell_versions(self) -> list[str]: |
| 507 |
""" |
| 508 |
Get a list of PowerShell versions to use. |
| 509 |
A target uses a single PowerShell version, but a controller may include additional versions for targets running on the controller. |
| 510 |
""" |
| 511 |
powershell_version_map = get_powershell_version_map() |
| 512 |
|
| 513 |
powershell_versions = [self.powershell.version] if self.powershell.version else [] |
| 514 |
powershell_versions.extend(target.powershell.version for target in self.targets if isinstance(target, ControllerConfig) and target.powershell.version) |
| 515 |
powershell_versions = sorted_versions(list(set(powershell_versions))) |
| 516 |
powershell_versions = [powershell_version_map[version] for version in powershell_versions] |
| 517 |
|
| 518 |
return powershell_versions |
| 519 |
|
| 520 |
|
| 521 |
class ControllerHostProfile[T: ControllerHostConfig](PosixProfile[T], DebuggableProfile[T], metaclass=abc.ABCMeta): |
| 522 |
"""Base class for profiles usable as a controller.""" |
| 523 |
|
| 524 |
@abc.abstractmethod |
| 525 |
def get_origin_controller_connection(self) -> Connection: |
| 526 |
"""Return a connection for accessing the host as a controller from the origin.""" |
| 527 |
|
| 528 |
@abc.abstractmethod |
| 529 |
def get_working_directory(self) -> str: |
| 530 |
"""Return the working directory for the host.""" |
| 531 |
|
| 532 |
|
| 533 |
class SshTargetHostProfile[THostConfig: HostConfig](HostProfile[THostConfig], metaclass=abc.ABCMeta): |
| 534 |
"""Base class for profiles offering SSH connectivity.""" |
| 535 |
|
| 536 |
@abc.abstractmethod |
| 537 |
def get_controller_target_connections(self) -> list[SshConnection]: |
| 538 |
"""Return SSH connection(s) for accessing the host as a target from the controller.""" |
| 539 |
|
| 540 |
|
| 541 |
class RemoteProfile[TRemoteConfig: RemoteConfig](SshTargetHostProfile[TRemoteConfig], metaclass=abc.ABCMeta): |
| 542 |
"""Base class for remote instance profiles.""" |
| 543 |
|
| 544 |
@property |
| 545 |
def name(self) -> str: |
| 546 |
"""The name of the host profile.""" |
| 547 |
return self.config.name |
| 548 |
|
| 549 |
@property |
| 550 |
def core_ci_state(self) -> t.Optional[dict[str, str]]: |
| 551 |
"""The saved Ansible Core CI state.""" |
| 552 |
return self.state.get('core_ci') |
| 553 |
|
| 554 |
@core_ci_state.setter |
| 555 |
def core_ci_state(self, value: dict[str, str]) -> None: |
| 556 |
"""The saved Ansible Core CI state.""" |
| 557 |
self.state['core_ci'] = value |
| 558 |
|
| 559 |
def pre_provision(self) -> None: |
| 560 |
"""Pre-provision the host before delegation.""" |
| 561 |
self.core_ci = self.create_core_ci(load=True) |
| 562 |
self.core_ci.start() |
| 563 |
|
| 564 |
self.core_ci_state = self.core_ci.save() |
| 565 |
|
| 566 |
def deprovision(self) -> None: |
| 567 |
"""Deprovision the host after delegation has completed.""" |
| 568 |
super().deprovision() |
| 569 |
|
| 570 |
if self.args.remote_terminate == TerminateMode.ALWAYS or (self.args.remote_terminate == TerminateMode.SUCCESS and self.args.success): |
| 571 |
self.delete_instance() |
| 572 |
|
| 573 |
@property |
| 574 |
def core_ci(self) -> t.Optional[AnsibleCoreCI]: |
| 575 |
"""Return the cached AnsibleCoreCI instance, if any, otherwise None.""" |
| 576 |
return self.cache.get('core_ci') |
| 577 |
|
| 578 |
@core_ci.setter |
| 579 |
def core_ci(self, value: AnsibleCoreCI) -> None: |
| 580 |
"""Cache the given AnsibleCoreCI instance.""" |
| 581 |
self.cache['core_ci'] = value |
| 582 |
|
| 583 |
def get_instance(self) -> t.Optional[AnsibleCoreCI]: |
| 584 |
"""Return the current AnsibleCoreCI instance, loading it if not already loaded.""" |
| 585 |
if not self.core_ci and self.core_ci_state: |
| 586 |
self.core_ci = self.create_core_ci(load=False) |
| 587 |
self.core_ci.load(self.core_ci_state) |
| 588 |
|
| 589 |
return self.core_ci |
| 590 |
|
| 591 |
def delete_instance(self) -> None: |
| 592 |
"""Delete the AnsibleCoreCI VM instance.""" |
| 593 |
core_ci = self.get_instance() |
| 594 |
|
| 595 |
if not core_ci: |
| 596 |
return # instance has not been provisioned |
| 597 |
|
| 598 |
core_ci.stop() |
| 599 |
|
| 600 |
def wait_for_instance(self) -> AnsibleCoreCI: |
| 601 |
"""Wait for an AnsibleCoreCI VM instance to become ready.""" |
| 602 |
core_ci = self.get_instance() |
| 603 |
core_ci.wait() |
| 604 |
|
| 605 |
return core_ci |
| 606 |
|
| 607 |
def create_core_ci(self, load: bool) -> AnsibleCoreCI: |
| 608 |
"""Create and return an AnsibleCoreCI instance.""" |
| 609 |
if not self.config.arch: |
| 610 |
raise InternalError(f'No arch specified for config: {self.config}') |
| 611 |
|
| 612 |
return AnsibleCoreCI( |
| 613 |
args=self.args, |
| 614 |
resource=VmResource( |
| 615 |
platform=self.config.platform, |
| 616 |
version=self.config.version, |
| 617 |
architecture=self.config.arch, |
| 618 |
provider=self.config.provider, |
| 619 |
tag='controller' if self.controller else 'target', |
| 620 |
), |
| 621 |
load=load, |
| 622 |
) |
| 623 |
|
| 624 |
|
| 625 |
class ControllerProfile(SshTargetHostProfile[ControllerConfig], PosixProfile[ControllerConfig], DebuggableProfile[ControllerConfig]): |
| 626 |
"""Host profile for the controller as a target.""" |
| 627 |
|
| 628 |
@property |
| 629 |
def name(self) -> str: |
| 630 |
"""The name of the host profile.""" |
| 631 |
return self.controller_profile.name |
| 632 |
|
| 633 |
@property |
| 634 |
def debugger_port(self) -> int: |
| 635 |
"""The pydevd port to use.""" |
| 636 |
return self.controller_profile.debugger_port |
| 637 |
|
| 638 |
def get_controller_target_connections(self) -> list[SshConnection]: |
| 639 |
"""Return SSH connection(s) for accessing the host as a target from the controller.""" |
| 640 |
settings = SshConnectionDetail( |
| 641 |
name='localhost', |
| 642 |
host='localhost', |
| 643 |
port=None, |
| 644 |
user='root', |
| 645 |
identity_file=SshKey(self.args).key, |
| 646 |
python_interpreter=self.args.controller_python.path, |
| 647 |
powershell_interpreter=self.args.controller_powershell.path, |
| 648 |
) |
| 649 |
|
| 650 |
return [SshConnection(self.args, settings)] |
| 651 |
|
| 652 |
|
| 653 |
class DockerProfile(ControllerHostProfile[DockerConfig], SshTargetHostProfile[DockerConfig], DebuggableProfile[DockerConfig]): |
| 654 |
"""Host profile for a docker instance.""" |
| 655 |
|
| 656 |
MARKER = 'ansible-test-marker' |
| 657 |
|
| 658 |
@dataclasses.dataclass(frozen=True) |
| 659 |
class InitConfig: |
| 660 |
"""Configuration details required to run the container init.""" |
| 661 |
|
| 662 |
options: list[str] |
| 663 |
command: str |
| 664 |
command_privileged: bool |
| 665 |
expected_mounts: tuple[CGroupMount, ...] |
| 666 |
|
| 667 |
@property |
| 668 |
def name(self) -> str: |
| 669 |
"""The name of the host profile.""" |
| 670 |
return self.config.name |
| 671 |
|
| 672 |
@property |
| 673 |
def container_name(self) -> t.Optional[str]: |
| 674 |
"""Return the stored container name, if any, otherwise None.""" |
| 675 |
return self.state.get('container_name') |
| 676 |
|
| 677 |
@container_name.setter |
| 678 |
def container_name(self, value: str) -> None: |
| 679 |
"""Store the given container name.""" |
| 680 |
self.state['container_name'] = value |
| 681 |
|
| 682 |
@property |
| 683 |
def cgroup_path(self) -> t.Optional[str]: |
| 684 |
"""Return the path to the cgroup v1 systemd hierarchy, if any, otherwise None.""" |
| 685 |
return self.state.get('cgroup_path') |
| 686 |
|
| 687 |
@cgroup_path.setter |
| 688 |
def cgroup_path(self, value: str) -> None: |
| 689 |
"""Store the path to the cgroup v1 systemd hierarchy.""" |
| 690 |
self.state['cgroup_path'] = value |
| 691 |
|
| 692 |
@property |
| 693 |
def label(self) -> str: |
| 694 |
"""Label to apply to resources related to this profile.""" |
| 695 |
return f'{"controller" if self.controller else "target"}' |
| 696 |
|
| 697 |
def provision(self) -> None: |
| 698 |
"""Provision the host before delegation.""" |
| 699 |
init_probe = self.args.dev_probe_cgroups is not None |
| 700 |
init_config = self.get_init_config() |
| 701 |
|
| 702 |
container = run_support_container( |
| 703 |
args=self.args, |
| 704 |
context='__test_hosts__', |
| 705 |
image=self.config.image, |
| 706 |
name=f'ansible-test-{self.label}', |
| 707 |
ports=[22], |
| 708 |
publish_ports=self.debugging_enabled or not self.controller, # SSH to the controller is not required unless remote debugging is enabled |
| 709 |
options=init_config.options, |
| 710 |
cleanup=False, |
| 711 |
cmd=self.build_init_command(init_config, init_probe), |
| 712 |
) |
| 713 |
|
| 714 |
if not container: |
| 715 |
if self.args.prime_containers: |
| 716 |
if init_config.command_privileged or init_probe: |
| 717 |
docker_pull(self.args, UTILITY_IMAGE) |
| 718 |
|
| 719 |
return |
| 720 |
|
| 721 |
self.container_name = container.name |
| 722 |
|
| 723 |
try: |
| 724 |
options = ['--pid', 'host', '--privileged'] |
| 725 |
|
| 726 |
if init_config.command and init_config.command_privileged: |
| 727 |
init_command = init_config.command |
| 728 |
|
| 729 |
if not init_probe: |
| 730 |
init_command += f' && {shlex.join(self.wake_command)}' |
| 731 |
|
| 732 |
cmd = ['nsenter', '-t', str(container.details.container.pid), '-m', '-p', 'sh', '-c', init_command] |
| 733 |
run_utility_container(self.args, f'ansible-test-init-{self.label}', cmd, options) |
| 734 |
|
| 735 |
if init_probe: |
| 736 |
check_container_cgroup_status(self.args, self.config, self.container_name, init_config.expected_mounts) |
| 737 |
|
| 738 |
cmd = ['nsenter', '-t', str(container.details.container.pid), '-m', '-p'] + self.wake_command |
| 739 |
run_utility_container(self.args, f'ansible-test-wake-{self.label}', cmd, options) |
| 740 |
except SubprocessError: |
| 741 |
display.info(f'Checking container "{self.container_name}" logs...') |
| 742 |
docker_logs(self.args, self.container_name) |
| 743 |
|
| 744 |
raise |
| 745 |
|
| 746 |
def get_init_config(self) -> InitConfig: |
| 747 |
"""Return init config for running under the current container engine.""" |
| 748 |
self.check_cgroup_requirements() |
| 749 |
|
| 750 |
engine = require_docker().command |
| 751 |
init_config = getattr(self, f'get_{engine}_init_config')() |
| 752 |
|
| 753 |
return init_config |
| 754 |
|
| 755 |
def get_podman_init_config(self) -> InitConfig: |
| 756 |
"""Return init config for running under Podman.""" |
| 757 |
options = self.get_common_run_options() |
| 758 |
command: t.Optional[str] = None |
| 759 |
command_privileged = False |
| 760 |
expected_mounts: tuple[CGroupMount, ...] |
| 761 |
|
| 762 |
cgroup_version = get_docker_info(self.args).cgroup_version |
| 763 |
|
| 764 |
# Podman 4.4.0 updated containers/common to 0.51.0, which removed the SYS_CHROOT capability from the default list. |
| 765 |
# This capability is needed by services such as sshd, so is unconditionally added here. |
| 766 |
# See: https://github.com/containers/podman/releases/tag/v4.4.0 |
| 767 |
# See: https://github.com/containers/common/releases/tag/v0.51.0 |
| 768 |
# See: https://github.com/containers/common/pull/1240 |
| 769 |
options.extend(('--cap-add', 'SYS_CHROOT')) |
| 770 |
|
| 771 |
# Without AUDIT_WRITE the following errors may appear in the system logs of a container after attempting to log in using SSH: |
| 772 |
# |
| 773 |
# fatal: linux_audit_write_entry failed: Operation not permitted |
| 774 |
# |
| 775 |
# This occurs when running containers as root when the container host provides audit support, but the user lacks the AUDIT_WRITE capability. |
| 776 |
# The AUDIT_WRITE capability is provided by docker by default, but not podman. |
| 777 |
# See: https://github.com/moby/moby/pull/7179 |
| 778 |
# |
| 779 |
# OpenSSH Portable requires AUDIT_WRITE when logging in with a TTY if the Linux audit feature was compiled in. |
| 780 |
# Containers with the feature enabled will require the AUDIT_WRITE capability when EPERM is returned while accessing the audit system. |
| 781 |
# See: https://github.com/openssh/openssh-portable/blob/2dc328023f60212cd29504fc05d849133ae47355/audit-linux.c#L90 |
| 782 |
# See: https://github.com/openssh/openssh-portable/blob/715c892f0a5295b391ae92c26ef4d6a86ea96e8e/loginrec.c#L476-L478 |
| 783 |
# |
| 784 |
# Some containers will be running a patched version of OpenSSH which blocks logins when EPERM is received while using the audit system. |
| 785 |
# These containers will require the AUDIT_WRITE capability when EPERM is returned while accessing the audit system. |
| 786 |
# See: https://src.fedoraproject.org/rpms/openssh/blob/f36/f/openssh-7.6p1-audit.patch |
| 787 |
# |
| 788 |
# Since only some containers carry the patch or enable the Linux audit feature in OpenSSH, this capability is enabled on a per-container basis. |
| 789 |
# No warning is provided when adding this capability, since there's not really anything the user can do about it. |
| 790 |
if self.config.audit == AuditMode.REQUIRED and detect_host_properties(self.args).audit_code == 'EPERM': |
| 791 |
options.extend(('--cap-add', 'AUDIT_WRITE')) |
| 792 |
|
| 793 |
# Without AUDIT_CONTROL the following errors may appear in the system logs of a container after attempting to log in using SSH: |
| 794 |
# |
| 795 |
# pam_loginuid(sshd:session): Error writing /proc/self/loginuid: Operation not permitted |
| 796 |
# pam_loginuid(sshd:session): set_loginuid failed |
| 797 |
# |
| 798 |
# Containers configured to use the pam_loginuid module will encounter this error. If the module is required, logins will fail. |
| 799 |
# Since most containers will have this configuration, the code to handle this issue is applied to all containers. |
| 800 |
# |
| 801 |
# This occurs when the loginuid is set on the container host and doesn't match the user on the container host which is running the container. |
| 802 |
# Container hosts which do not use systemd are likely to leave the loginuid unset and thus be unaffected. |
| 803 |
# The most common source of a mismatch is the use of sudo to run ansible-test, which changes the uid but cannot change the loginuid. |
| 804 |
# This condition typically occurs only under podman, since the loginuid is inherited from the current user. |
| 805 |
# See: https://github.com/containers/podman/issues/13012#issuecomment-1034049725 |
| 806 |
# |
| 807 |
# This condition is detected by querying the loginuid of a container running on the container host. |
| 808 |
# When it occurs, a warning is displayed and the AUDIT_CONTROL capability is added to containers to work around the issue. |
| 809 |
# The warning serves as notice to the user that their usage of ansible-test is responsible for the additional capability requirement. |
| 810 |
if (loginuid := detect_host_properties(self.args).loginuid) not in (0, LOGINUID_NOT_SET, None): |
| 811 |
display.warning(f'Running containers with capability AUDIT_CONTROL since the container loginuid ({loginuid}) is incorrect. ' |
| 812 |
'This is most likely due to use of sudo to run ansible-test when loginuid is already set.', unique=True) |
| 813 |
|
| 814 |
options.extend(('--cap-add', 'AUDIT_CONTROL')) |
| 815 |
|
| 816 |
if self.config.cgroup == CGroupVersion.NONE: |
| 817 |
# Containers which do not require cgroup do not use systemd. |
| 818 |
|
| 819 |
options.extend(( |
| 820 |
# Disabling systemd support in Podman will allow these containers to work on hosts without systemd. |
| 821 |
# Without this, running a container on a host without systemd results in errors such as (from crun): |
| 822 |
# Error: crun: error stat'ing file `/sys/fs/cgroup/systemd`: No such file or directory: |
| 823 |
# A similar error occurs when using runc: |
| 824 |
# OCI runtime attempted to invoke a command that was not found |
| 825 |
'--systemd', 'false', |
| 826 |
# A private cgroup namespace limits what is visible in /proc/*/cgroup. |
| 827 |
'--cgroupns', 'private', |
| 828 |
# Mounting a tmpfs overrides the cgroup mount(s) that would otherwise be provided by Podman. |
| 829 |
# This helps provide a consistent container environment across various container host configurations. |
| 830 |
'--tmpfs', '/sys/fs/cgroup', |
| 831 |
)) |
| 832 |
|
| 833 |
expected_mounts = ( |
| 834 |
CGroupMount(path=CGroupPath.ROOT, type=MountType.TMPFS, writable=True, state=None), |
| 835 |
) |
| 836 |
elif self.config.cgroup in (CGroupVersion.V1_V2, CGroupVersion.V1_ONLY) and cgroup_version == 1: |
| 837 |
# Podman hosts providing cgroup v1 will automatically bind mount the systemd hierarchy read-write in the container. |
| 838 |
# They will also create a dedicated cgroup v1 systemd hierarchy for the container. |
| 839 |
# On hosts with systemd this path is: /sys/fs/cgroup/systemd/libpod_parent/libpod-{container_id}/ |
| 840 |
# On hosts without systemd this path is: /sys/fs/cgroup/systemd/{container_id}/ |
| 841 |
|
| 842 |
options.extend(( |
| 843 |
# Force Podman to enable systemd support since a command may be used later (to support pre-init diagnostics). |
| 844 |
'--systemd', 'always', |
| 845 |
# The host namespace must be used to permit the container to access the cgroup v1 systemd hierarchy created by Podman. |
| 846 |
'--cgroupns', 'host', |
| 847 |
# Mask the host cgroup tmpfs mount to avoid exposing the host cgroup v1 hierarchies (or cgroup v2 hybrid) to the container. |
| 848 |
# Podman will provide a cgroup v1 systemd hierarchy on top of this. |
| 849 |
'--tmpfs', '/sys/fs/cgroup', |
| 850 |
)) |
| 851 |
|
| 852 |
self.check_systemd_cgroup_v1(options) # podman |
| 853 |
|
| 854 |
expected_mounts = ( |
| 855 |
CGroupMount(path=CGroupPath.ROOT, type=MountType.TMPFS, writable=True, state=None), |
| 856 |
# The mount point can be writable or not. |
| 857 |
# The reason for the variation is not known. |
| 858 |
CGroupMount(path=CGroupPath.SYSTEMD, type=MountType.CGROUP_V1, writable=None, state=CGroupState.HOST), |
| 859 |
# The filesystem type can be tmpfs or devtmpfs. |
| 860 |
# The reason for the variation is not known. |
| 861 |
CGroupMount(path=CGroupPath.SYSTEMD_RELEASE_AGENT, type=None, writable=False, state=None), |
| 862 |
) |
| 863 |
elif self.config.cgroup in (CGroupVersion.V1_V2, CGroupVersion.V2_ONLY) and cgroup_version == 2: |
| 864 |
# Podman hosts providing cgroup v2 will give each container a read-write cgroup mount. |
| 865 |
|
| 866 |
options.extend(( |
| 867 |
# Force Podman to enable systemd support since a command may be used later (to support pre-init diagnostics). |
| 868 |
'--systemd', 'always', |
| 869 |
# A private cgroup namespace is used to avoid exposing the host cgroup to the container. |
| 870 |
'--cgroupns', 'private', |
| 871 |
)) |
| 872 |
|
| 873 |
expected_mounts = ( |
| 874 |
CGroupMount(path=CGroupPath.ROOT, type=MountType.CGROUP_V2, writable=True, state=CGroupState.PRIVATE), |
| 875 |
) |
| 876 |
elif self.config.cgroup == CGroupVersion.V1_ONLY and cgroup_version == 2: |
| 877 |
# Containers which require cgroup v1 need explicit volume mounts on container hosts not providing that version. |
| 878 |
# We must put the container PID 1 into the cgroup v1 systemd hierarchy we create. |
| 879 |
cgroup_path = self.create_systemd_cgroup_v1() # podman |
| 880 |
command = f'echo 1 > {cgroup_path}/cgroup.procs' |
| 881 |
|
| 882 |
options.extend(( |
| 883 |
# Force Podman to enable systemd support since a command is being provided. |
| 884 |
'--systemd', 'always', |
| 885 |
# A private cgroup namespace is required. Using the host cgroup namespace results in errors such as the following (from crun): |
| 886 |
# Error: OCI runtime error: mount `/sys/fs/cgroup` to '/sys/fs/cgroup': Invalid argument |
| 887 |
# A similar error occurs when using runc: |
| 888 |
# Error: OCI runtime error: runc create failed: unable to start container process: error during container init: |
| 889 |
# error mounting "/sys/fs/cgroup" to rootfs at "/sys/fs/cgroup": mount /sys/fs/cgroup:/sys/fs/cgroup (via /proc/self/fd/7), flags: 0x1000: |
| 890 |
# invalid argument |
| 891 |
'--cgroupns', 'private', |
| 892 |
# Unlike Docker, Podman ignores a /sys/fs/cgroup tmpfs mount, instead exposing a cgroup v2 mount. |
| 893 |
# The exposed volume will be read-write, but the container will have its own private namespace. |
| 894 |
# Provide a read-only cgroup v1 systemd hierarchy under which the dedicated ansible-test cgroup will be mounted read-write. |
| 895 |
# Without this systemd will fail while attempting to mount the cgroup v1 systemd hierarchy. |
| 896 |
# Podman doesn't support using a tmpfs for this. Attempting to do so results in an error (from crun): |
| 897 |
# Error: OCI runtime error: read: Invalid argument |
| 898 |
# A similar error occurs when using runc: |
| 899 |
# Error: OCI runtime error: runc create failed: unable to start container process: error during container init: |
| 900 |
# error mounting "tmpfs" to rootfs at "/sys/fs/cgroup/systemd": tmpcopyup: failed to copy /sys/fs/cgroup/systemd to /proc/self/fd/7 |
| 901 |
# (/tmp/runctop3876247619/runctmpdir1460907418): read /proc/self/fd/7/cgroup.kill: invalid argument |
| 902 |
'--volume', '/sys/fs/cgroup/systemd:/sys/fs/cgroup/systemd:ro', |
| 903 |
# Provide the container access to the cgroup v1 systemd hierarchy created by ansible-test. |
| 904 |
'--volume', f'{cgroup_path}:{cgroup_path}:rw', |
| 905 |
)) |
| 906 |
|
| 907 |
expected_mounts = ( |
| 908 |
CGroupMount(path=CGroupPath.ROOT, type=MountType.CGROUP_V2, writable=True, state=CGroupState.PRIVATE), |
| 909 |
CGroupMount(path=CGroupPath.SYSTEMD, type=MountType.CGROUP_V1, writable=False, state=CGroupState.SHADOWED), |
| 910 |
CGroupMount(path=cgroup_path, type=MountType.CGROUP_V1, writable=True, state=CGroupState.HOST), |
| 911 |
) |
| 912 |
else: |
| 913 |
raise InternalError(f'Unhandled cgroup configuration: {self.config.cgroup} on cgroup v{cgroup_version}.') |
| 914 |
|
| 915 |
return self.InitConfig( |
| 916 |
options=options, |
| 917 |
command=command, |
| 918 |
command_privileged=command_privileged, |
| 919 |
expected_mounts=expected_mounts, |
| 920 |
) |
| 921 |
|
| 922 |
def get_docker_init_config(self) -> InitConfig: |
| 923 |
"""Return init config for running under Docker.""" |
| 924 |
options = self.get_common_run_options() |
| 925 |
command: t.Optional[str] = None |
| 926 |
command_privileged = False |
| 927 |
expected_mounts: tuple[CGroupMount, ...] |
| 928 |
|
| 929 |
docker_socket = '/var/run/docker.sock' |
| 930 |
|
| 931 |
if get_docker_hostname() != 'localhost' or os.path.exists(docker_socket): |
| 932 |
options.extend(['--volume', f'{docker_socket}:{docker_socket}']) |
| 933 |
|
| 934 |
cgroup_version = get_docker_info(self.args).cgroup_version |
| 935 |
|
| 936 |
if self.config.cgroup == CGroupVersion.NONE: |
| 937 |
# Containers which do not require cgroup do not use systemd. |
| 938 |
|
| 939 |
if get_docker_info(self.args).cgroupns_option_supported: |
| 940 |
# Use the `--cgroupns` option if it is supported. |
| 941 |
# Older servers which do not support the option use the host group namespace. |
| 942 |
# Older clients which do not support the option cause newer servers to use the host cgroup namespace (cgroup v1 only). |
| 943 |
# See: https://github.com/moby/moby/blob/master/api/server/router/container/container_routes.go#L512-L517 |
| 944 |
# If the host cgroup namespace is used, cgroup information will be visible, but the cgroup mounts will be unavailable due to the tmpfs below. |
| 945 |
options.extend(( |
| 946 |
# A private cgroup namespace limits what is visible in /proc/*/cgroup. |
| 947 |
'--cgroupns', 'private', |
| 948 |
)) |
| 949 |
|
| 950 |
options.extend(( |
| 951 |
# Mounting a tmpfs overrides the cgroup mount(s) that would otherwise be provided by Docker. |
| 952 |
# This helps provide a consistent container environment across various container host configurations. |
| 953 |
'--tmpfs', '/sys/fs/cgroup', |
| 954 |
)) |
| 955 |
|
| 956 |
expected_mounts = ( |
| 957 |
CGroupMount(path=CGroupPath.ROOT, type=MountType.TMPFS, writable=True, state=None), |
| 958 |
) |
| 959 |
elif self.config.cgroup in (CGroupVersion.V1_V2, CGroupVersion.V1_ONLY) and cgroup_version == 1: |
| 960 |
# Docker hosts providing cgroup v1 will automatically bind mount the systemd hierarchy read-only in the container. |
| 961 |
# They will also create a dedicated cgroup v1 systemd hierarchy for the container. |
| 962 |
# The cgroup v1 system hierarchy path is: /sys/fs/cgroup/systemd/{container_id}/ |
| 963 |
|
| 964 |
if get_docker_info(self.args).cgroupns_option_supported: |
| 965 |
# Use the `--cgroupns` option if it is supported. |
| 966 |
# Older servers which do not support the option use the host group namespace. |
| 967 |
# Older clients which do not support the option cause newer servers to use the host cgroup namespace (cgroup v1 only). |
| 968 |
# See: https://github.com/moby/moby/blob/master/api/server/router/container/container_routes.go#L512-L517 |
| 969 |
options.extend(( |
| 970 |
# The host cgroup namespace must be used. |
| 971 |
# Otherwise, /proc/1/cgroup will report "/" for the cgroup path, which is incorrect. |
| 972 |
# See: https://github.com/systemd/systemd/issues/19245#issuecomment-815954506 |
| 973 |
# It is set here to avoid relying on the current Docker configuration. |
| 974 |
'--cgroupns', 'host', |
| 975 |
)) |
| 976 |
|
| 977 |
options.extend(( |
| 978 |
# Mask the host cgroup tmpfs mount to avoid exposing the host cgroup v1 hierarchies (or cgroup v2 hybrid) to the container. |
| 979 |
'--tmpfs', '/sys/fs/cgroup', |
| 980 |
# A cgroup v1 systemd hierarchy needs to be mounted read-write over the read-only one provided by Docker. |
| 981 |
# Alternatives were tested, but were unusable due to various issues: |
| 982 |
# - Attempting to remount the existing mount point read-write will result in a "mount point is busy" error. |
| 983 |
# - Adding the entire "/sys/fs/cgroup" mount will expose hierarchies other than systemd. |
| 984 |
# If the host is a cgroup v2 hybrid host it would also expose the /sys/fs/cgroup/unified/ hierarchy read-write. |
| 985 |
# On older systems, such as an Ubuntu 18.04 host, a dedicated v2 cgroup would not be used, exposing the host cgroups to the container. |
| 986 |
'--volume', '/sys/fs/cgroup/systemd:/sys/fs/cgroup/systemd:rw', |
| 987 |
)) |
| 988 |
|
| 989 |
self.check_systemd_cgroup_v1(options) # docker |
| 990 |
|
| 991 |
expected_mounts = ( |
| 992 |
CGroupMount(path=CGroupPath.ROOT, type=MountType.TMPFS, writable=True, state=None), |
| 993 |
CGroupMount(path=CGroupPath.SYSTEMD, type=MountType.CGROUP_V1, writable=True, state=CGroupState.HOST), |
| 994 |
) |
| 995 |
elif self.config.cgroup in (CGroupVersion.V1_V2, CGroupVersion.V2_ONLY) and cgroup_version == 2: |
| 996 |
# Docker hosts providing cgroup v2 will give each container a read-only cgroup mount. |
| 997 |
# It must be remounted read-write before systemd starts. |
| 998 |
# This must be done in a privileged container, otherwise a "permission denied" error can occur. |
| 999 |
command = 'mount -o remount,rw /sys/fs/cgroup/' |
| 1000 |
command_privileged = True |
| 1001 |
|
| 1002 |
options.extend(( |
| 1003 |
# A private cgroup namespace is used to avoid exposing the host cgroup to the container. |
| 1004 |
# This matches the behavior in Podman 1.7.0 and later, which select cgroupns 'host' mode for cgroup v1 and 'private' mode for cgroup v2. |
| 1005 |
# See: https://github.com/containers/podman/pull/4374 |
| 1006 |
# See: https://github.com/containers/podman/blob/main/RELEASE_NOTES.md#170 |
| 1007 |
'--cgroupns', 'private', |
| 1008 |
)) |
| 1009 |
|
| 1010 |
expected_mounts = ( |
| 1011 |
CGroupMount(path=CGroupPath.ROOT, type=MountType.CGROUP_V2, writable=True, state=CGroupState.PRIVATE), |
| 1012 |
) |
| 1013 |
elif self.config.cgroup == CGroupVersion.V1_ONLY and cgroup_version == 2: |
| 1014 |
# Containers which require cgroup v1 need explicit volume mounts on container hosts not providing that version. |
| 1015 |
# We must put the container PID 1 into the cgroup v1 systemd hierarchy we create. |
| 1016 |
cgroup_path = self.create_systemd_cgroup_v1() # docker |
| 1017 |
command = f'echo 1 > {cgroup_path}/cgroup.procs' |
| 1018 |
|
| 1019 |
options.extend(( |
| 1020 |
# A private cgroup namespace is used since no access to the host cgroup namespace is required. |
| 1021 |
# This matches the configuration used for running cgroup v1 containers under Podman. |
| 1022 |
'--cgroupns', 'private', |
| 1023 |
# Provide a read-write tmpfs filesystem to support additional cgroup mount points. |
| 1024 |
# Without this Docker will provide a read-only cgroup2 mount instead. |
| 1025 |
'--tmpfs', '/sys/fs/cgroup', |
| 1026 |
# Provide a read-write tmpfs filesystem to simulate a systemd cgroup v1 hierarchy. |
| 1027 |
# Without this systemd will fail while attempting to mount the cgroup v1 systemd hierarchy. |
| 1028 |
'--tmpfs', '/sys/fs/cgroup/systemd', |
| 1029 |
# Provide the container access to the cgroup v1 systemd hierarchy created by ansible-test. |
| 1030 |
'--volume', f'{cgroup_path}:{cgroup_path}:rw', |
| 1031 |
)) |
| 1032 |
|
| 1033 |
expected_mounts = ( |
| 1034 |
CGroupMount(path=CGroupPath.ROOT, type=MountType.TMPFS, writable=True, state=None), |
| 1035 |
CGroupMount(path=CGroupPath.SYSTEMD, type=MountType.TMPFS, writable=True, state=None), |
| 1036 |
CGroupMount(path=cgroup_path, type=MountType.CGROUP_V1, writable=True, state=CGroupState.HOST), |
| 1037 |
) |
| 1038 |
else: |
| 1039 |
raise InternalError(f'Unhandled cgroup configuration: {self.config.cgroup} on cgroup v{cgroup_version}.') |
| 1040 |
|
| 1041 |
return self.InitConfig( |
| 1042 |
options=options, |
| 1043 |
command=command, |
| 1044 |
command_privileged=command_privileged, |
| 1045 |
expected_mounts=expected_mounts, |
| 1046 |
) |
| 1047 |
|
| 1048 |
def build_init_command(self, init_config: InitConfig, sleep: bool) -> t.Optional[list[str]]: |
| 1049 |
""" |
| 1050 |
Build and return the command to start in the container. |
| 1051 |
Returns None if the default command for the container should be used. |
| 1052 |
|
| 1053 |
The sleep duration below was selected to: |
| 1054 |
|
| 1055 |
- Allow enough time to perform necessary operations in the container before waking it. |
| 1056 |
- Make the delay obvious if the wake command doesn't run or succeed. |
| 1057 |
- Avoid hanging indefinitely or for an unreasonably long time. |
| 1058 |
|
| 1059 |
NOTE: The container must have a POSIX-compliant default shell "sh" with a non-builtin "sleep" command. |
| 1060 |
The "sleep" command is invoked through "env" to avoid using a shell builtin "sleep" (if present). |
| 1061 |
""" |
| 1062 |
command = '' |
| 1063 |
|
| 1064 |
if init_config.command and not init_config.command_privileged: |
| 1065 |
command += f'{init_config.command} && ' |
| 1066 |
|
| 1067 |
if sleep or init_config.command_privileged: |
| 1068 |
command += 'env sleep 60 ; ' |
| 1069 |
|
| 1070 |
if not command: |
| 1071 |
return None |
| 1072 |
|
| 1073 |
docker_pull(self.args, self.config.image) |
| 1074 |
inspect = docker_image_inspect(self.args, self.config.image) |
| 1075 |
|
| 1076 |
command += f'exec {shlex.join(inspect.cmd)}' |
| 1077 |
|
| 1078 |
return ['sh', '-c', command] |
| 1079 |
|
| 1080 |
@property |
| 1081 |
def wake_command(self) -> list[str]: |
| 1082 |
""" |
| 1083 |
The command used to wake the container from sleep. |
| 1084 |
This will be run inside our utility container, so the command used does not need to be present in the container being woken up. |
| 1085 |
""" |
| 1086 |
return ['pkill', 'sleep'] |
| 1087 |
|
| 1088 |
def check_systemd_cgroup_v1(self, options: list[str]) -> None: |
| 1089 |
"""Check the cgroup v1 systemd hierarchy to verify it is writeable for our container.""" |
| 1090 |
probe_script = (read_text_file(os.path.join(ANSIBLE_TEST_TARGET_ROOT, 'setup', 'check_systemd_cgroup_v1.sh')) |
| 1091 |
.replace('@MARKER@', self.MARKER) |
| 1092 |
.replace('@LABEL@', f'{self.label}-{self.args.session_name}')) |
| 1093 |
|
| 1094 |
cmd = ['sh'] |
| 1095 |
|
| 1096 |
try: |
| 1097 |
run_utility_container(self.args, f'ansible-test-cgroup-check-{self.label}', cmd, options, data=probe_script) |
| 1098 |
except SubprocessError as ex: |
| 1099 |
if error := self.extract_error(ex.stderr): |
| 1100 |
raise ControlGroupError(self.args, 'Unable to create a v1 cgroup within the systemd hierarchy.\n' |
| 1101 |
f'Reason: {error}') from ex # cgroup probe failed |
| 1102 |
|
| 1103 |
raise |
| 1104 |
|
| 1105 |
def create_systemd_cgroup_v1(self) -> str: |
| 1106 |
"""Create a unique ansible-test cgroup in the v1 systemd hierarchy and return its path.""" |
| 1107 |
self.cgroup_path = f'/sys/fs/cgroup/systemd/ansible-test-{self.label}-{self.args.session_name}' |
| 1108 |
|
| 1109 |
# Privileged mode is required to create the cgroup directories on some hosts, such as Fedora 36 and RHEL 9.0. |
| 1110 |
# The mkdir command will fail with "Permission denied" otherwise. |
| 1111 |
options = ['--volume', '/sys/fs/cgroup/systemd:/sys/fs/cgroup/systemd:rw', '--privileged'] |
| 1112 |
cmd = ['sh', '-c', f'>&2 echo {shlex.quote(self.MARKER)} && mkdir {shlex.quote(self.cgroup_path)}'] |
| 1113 |
|
| 1114 |
try: |
| 1115 |
run_utility_container(self.args, f'ansible-test-cgroup-create-{self.label}', cmd, options) |
| 1116 |
except SubprocessError as ex: |
| 1117 |
if error := self.extract_error(ex.stderr): |
| 1118 |
raise ControlGroupError(self.args, f'Unable to create a v1 cgroup within the systemd hierarchy.\n' |
| 1119 |
f'Reason: {error}') from ex # cgroup create permission denied |
| 1120 |
|
| 1121 |
raise |
| 1122 |
|
| 1123 |
return self.cgroup_path |
| 1124 |
|
| 1125 |
@property |
| 1126 |
def delete_systemd_cgroup_v1_command(self) -> list[str]: |
| 1127 |
"""The command used to remove the previously created ansible-test cgroup in the v1 systemd hierarchy.""" |
| 1128 |
return ['find', self.cgroup_path, '-type', 'd', '-delete'] |
| 1129 |
|
| 1130 |
def delete_systemd_cgroup_v1(self) -> None: |
| 1131 |
"""Delete a previously created ansible-test cgroup in the v1 systemd hierarchy.""" |
| 1132 |
# Privileged mode is required to remove the cgroup directories on some hosts, such as Fedora 36 and RHEL 9.0. |
| 1133 |
# The BusyBox find utility will report "Permission denied" otherwise, although it still exits with a status code of 0. |
| 1134 |
options = ['--volume', '/sys/fs/cgroup/systemd:/sys/fs/cgroup/systemd:rw', '--privileged'] |
| 1135 |
cmd = ['sh', '-c', f'>&2 echo {shlex.quote(self.MARKER)} && {shlex.join(self.delete_systemd_cgroup_v1_command)}'] |
| 1136 |
|
| 1137 |
try: |
| 1138 |
run_utility_container(self.args, f'ansible-test-cgroup-delete-{self.label}', cmd, options) |
| 1139 |
except SubprocessError as ex: |
| 1140 |
if error := self.extract_error(ex.stderr): |
| 1141 |
if error.endswith(': No such file or directory'): |
| 1142 |
return |
| 1143 |
|
| 1144 |
display.error(str(ex)) |
| 1145 |
|
| 1146 |
def extract_error(self, value: str) -> t.Optional[str]: |
| 1147 |
""" |
| 1148 |
Extract the ansible-test portion of the error message from the given value and return it. |
| 1149 |
Returns None if no ansible-test marker was found. |
| 1150 |
""" |
| 1151 |
lines = value.strip().splitlines() |
| 1152 |
|
| 1153 |
try: |
| 1154 |
idx = lines.index(self.MARKER) |
| 1155 |
except ValueError: |
| 1156 |
return None |
| 1157 |
|
| 1158 |
lines = lines[idx + 1:] |
| 1159 |
message = '\n'.join(lines) |
| 1160 |
|
| 1161 |
return message |
| 1162 |
|
| 1163 |
def check_cgroup_requirements(self) -> None: |
| 1164 |
"""Check cgroup requirements for the container.""" |
| 1165 |
cgroup_version = get_docker_info(self.args).cgroup_version |
| 1166 |
|
| 1167 |
if cgroup_version not in (1, 2): |
| 1168 |
raise ApplicationError(f'The container host provides cgroup v{cgroup_version}, but only version v1 and v2 are supported.') |
| 1169 |
|
| 1170 |
# Stop early for containers which require cgroup v2 when the container host does not provide it. |
| 1171 |
# None of the containers included with ansible-test currently use this configuration. |
| 1172 |
# Support for v2-only was added in preparation for the eventual removal of cgroup v1 support from systemd after EOY 2023. |
| 1173 |
# See: https://github.com/systemd/systemd/pull/24086 |
| 1174 |
if self.config.cgroup == CGroupVersion.V2_ONLY and cgroup_version != 2: |
| 1175 |
raise ApplicationError(f'Container {self.config.name} requires cgroup v2 but the container host provides cgroup v{cgroup_version}.') |
| 1176 |
|
| 1177 |
# Containers which use old versions of systemd (earlier than version 226) require cgroup v1 support. |
| 1178 |
# If the host is a cgroup v2 (unified) host, changes must be made to how the container is run. |
| 1179 |
# |
| 1180 |
# See: https://github.com/systemd/systemd/blob/main/NEWS |
| 1181 |
# Under the "CHANGES WITH 226" section: |
| 1182 |
# > systemd now optionally supports the new Linux kernel "unified" control group hierarchy. |
| 1183 |
# |
| 1184 |
# NOTE: The container host must have the cgroup v1 mount already present. |
| 1185 |
# If the container is run rootless, the user it runs under must have permissions to the mount. |
| 1186 |
# |
| 1187 |
# The following commands can be used to make the mount available: |
| 1188 |
# |
| 1189 |
# mkdir /sys/fs/cgroup/systemd |
| 1190 |
# mount cgroup -t cgroup /sys/fs/cgroup/systemd -o none,name=systemd,xattr |
| 1191 |
# chown -R {user}:{group} /sys/fs/cgroup/systemd # only when rootless |
| 1192 |
# |
| 1193 |
# See: https://github.com/containers/crun/blob/main/crun.1.md#runocisystemdforce_cgroup_v1path |
| 1194 |
if self.config.cgroup == CGroupVersion.V1_ONLY or (self.config.cgroup != CGroupVersion.NONE and get_docker_info(self.args).cgroup_version == 1): |
| 1195 |
if (cgroup_v1 := detect_host_properties(self.args).cgroup_v1) != SystemdControlGroupV1Status.VALID: |
| 1196 |
if self.config.cgroup == CGroupVersion.V1_ONLY: |
| 1197 |
if get_docker_info(self.args).cgroup_version == 2: |
| 1198 |
reason = f'Container {self.config.name} requires cgroup v1, but the container host only provides cgroup v2.' |
| 1199 |
else: |
| 1200 |
reason = f'Container {self.config.name} requires cgroup v1, but the container host does not appear to be running systemd.' |
| 1201 |
else: |
| 1202 |
reason = 'The container host provides cgroup v1, but does not appear to be running systemd.' |
| 1203 |
|
| 1204 |
reason += f'\n{cgroup_v1.value}' |
| 1205 |
|
| 1206 |
raise ControlGroupError(self.args, reason) # cgroup probe reported invalid state |
| 1207 |
|
| 1208 |
def setup(self) -> None: |
| 1209 |
"""Perform out-of-band setup before delegation.""" |
| 1210 |
bootstrapper = BootstrapDocker( |
| 1211 |
controller=self.controller, |
| 1212 |
python_interpreters=self.get_python_interpreters(), |
| 1213 |
powershell_versions=self.get_powershell_versions(), |
| 1214 |
ssh_key=SshKey(self.args), |
| 1215 |
) |
| 1216 |
|
| 1217 |
setup_sh = bootstrapper.get_script() |
| 1218 |
shell = setup_sh.splitlines()[0][2:] |
| 1219 |
|
| 1220 |
try: |
| 1221 |
docker_exec(self.args, self.container_name, [shell], data=setup_sh, capture=False) |
| 1222 |
except SubprocessError: |
| 1223 |
display.info(f'Checking container "{self.container_name}" logs...') |
| 1224 |
docker_logs(self.args, self.container_name) |
| 1225 |
raise |
| 1226 |
|
| 1227 |
if self.debugging_enabled: |
| 1228 |
self.enable_debugger_forwarding(self.get_ssh_connection_detail(HostType.origin)) |
| 1229 |
|
| 1230 |
def deprovision(self) -> None: |
| 1231 |
"""Deprovision the host after delegation has completed.""" |
| 1232 |
super().deprovision() |
| 1233 |
|
| 1234 |
container_exists = False |
| 1235 |
|
| 1236 |
if self.container_name: |
| 1237 |
if self.args.docker_terminate == TerminateMode.ALWAYS or (self.args.docker_terminate == TerminateMode.SUCCESS and self.args.success): |
| 1238 |
docker_rm(self.args, self.container_name) |
| 1239 |
else: |
| 1240 |
container_exists = True |
| 1241 |
|
| 1242 |
if self.cgroup_path: |
| 1243 |
if container_exists: |
| 1244 |
display.notice(f'Remember to run `{require_docker().command} rm -f {self.container_name}` when finished testing. ' |
| 1245 |
f'Then run `{shlex.join(self.delete_systemd_cgroup_v1_command)}` on the container host.') |
| 1246 |
else: |
| 1247 |
self.delete_systemd_cgroup_v1() |
| 1248 |
elif container_exists: |
| 1249 |
display.notice(f'Remember to run `{require_docker().command} rm -f {self.container_name}` when finished testing.') |
| 1250 |
|
| 1251 |
def wait(self) -> None: |
| 1252 |
"""Wait for the instance to be ready. Executed before delegation for the controller and after delegation for targets.""" |
| 1253 |
if not self.controller: |
| 1254 |
con = self.get_controller_target_connections()[0] |
| 1255 |
last_error = '' |
| 1256 |
|
| 1257 |
for dummy in range(1, 10): |
| 1258 |
try: |
| 1259 |
con.run(['id'], capture=True) |
| 1260 |
except SubprocessError as ex: |
| 1261 |
if 'Permission denied' in ex.message: |
| 1262 |
raise |
| 1263 |
|
| 1264 |
last_error = str(ex) |
| 1265 |
time.sleep(1) |
| 1266 |
else: |
| 1267 |
return |
| 1268 |
|
| 1269 |
display.info('Checking SSH debug output...') |
| 1270 |
display.info(last_error) |
| 1271 |
|
| 1272 |
if not self.args.delegate and not self.args.host_path: |
| 1273 |
|
| 1274 |
def callback() -> None: |
| 1275 |
"""Callback to run during error display.""" |
| 1276 |
self.on_target_failure() # when the controller is not delegated, report failures immediately |
| 1277 |
|
| 1278 |
else: |
| 1279 |
callback = None |
| 1280 |
|
| 1281 |
raise HostConnectionError(f'Timeout waiting for {self.config.name} container {self.container_name}.', callback) |
| 1282 |
|
| 1283 |
def get_ssh_connection_detail(self, host_type: str) -> SshConnectionDetail: |
| 1284 |
"""Return SSH connection detail for the specified host type.""" |
| 1285 |
containers = get_container_database(self.args) |
| 1286 |
access = containers.data[host_type]['__test_hosts__'][self.container_name] |
| 1287 |
|
| 1288 |
host = access.host_ip |
| 1289 |
port = dict(access.port_map())[22] |
| 1290 |
|
| 1291 |
settings = SshConnectionDetail( |
| 1292 |
name=self.config.name, |
| 1293 |
user='root', |
| 1294 |
host=host, |
| 1295 |
port=port, |
| 1296 |
identity_file=SshKey(self.args).key, |
| 1297 |
python_interpreter=self.python.path, |
| 1298 |
powershell_interpreter=self.powershell.path, |
| 1299 |
# CentOS 6 uses OpenSSH 5.3, making it incompatible with the default configuration of OpenSSH 8.8 and later clients. |
| 1300 |
# Since only CentOS 6 is affected, and it is only supported by ansible-core 2.12, support for RSA SHA-1 is simply hard-coded here. |
| 1301 |
# A substring is used to allow custom containers to work, not just the one provided with ansible-test. |
| 1302 |
enable_rsa_sha1='centos6' in self.config.image, |
| 1303 |
) |
| 1304 |
|
| 1305 |
return settings |
| 1306 |
|
| 1307 |
def get_controller_target_connections(self) -> list[SshConnection]: |
| 1308 |
"""Return SSH connection(s) for accessing the host as a target from the controller.""" |
| 1309 |
return [SshConnection(self.args, self.get_ssh_connection_detail(HostType.control))] |
| 1310 |
|
| 1311 |
def get_origin_controller_connection(self) -> DockerConnection: |
| 1312 |
"""Return a connection for accessing the host as a controller from the origin.""" |
| 1313 |
return DockerConnection(self.args, self.container_name) |
| 1314 |
|
| 1315 |
def get_working_directory(self) -> str: |
| 1316 |
"""Return the working directory for the host.""" |
| 1317 |
return '/root' |
| 1318 |
|
| 1319 |
def on_target_failure(self) -> None: |
| 1320 |
"""Executed during failure handling if this profile is a target.""" |
| 1321 |
display.info(f'Checking container "{self.container_name}" logs...') |
| 1322 |
|
| 1323 |
try: |
| 1324 |
docker_logs(self.args, self.container_name) |
| 1325 |
except SubprocessError as ex: |
| 1326 |
display.error(str(ex)) |
| 1327 |
|
| 1328 |
if self.config.cgroup != CGroupVersion.NONE: |
| 1329 |
# Containers with cgroup support are assumed to be running systemd. |
| 1330 |
display.info(f'Checking container "{self.container_name}" systemd logs...') |
| 1331 |
|
| 1332 |
try: |
| 1333 |
docker_exec(self.args, self.container_name, ['journalctl'], capture=False) |
| 1334 |
except SubprocessError as ex: |
| 1335 |
display.error(str(ex)) |
| 1336 |
|
| 1337 |
display.error(f'Connection to container "{self.container_name}" failed. See logs and original error above.') |
| 1338 |
|
| 1339 |
def get_common_run_options(self) -> list[str]: |
| 1340 |
"""Return a list of options needed to run the container.""" |
| 1341 |
options = [ |
| 1342 |
# These temporary mount points need to be created at run time when using Docker. |
| 1343 |
# They are automatically provided by Podman, but will be overridden by VOLUME instructions for the container, if they exist. |
| 1344 |
# If supporting containers with VOLUME instructions is not desired, these options could be limited to use with Docker. |
| 1345 |
# See: https://github.com/containers/podman/pull/1318 |
| 1346 |
# Previously they were handled by the VOLUME instruction during container image creation. |
| 1347 |
# However, that approach creates anonymous volumes when running the container, which are then left behind after the container is deleted. |
| 1348 |
# These options eliminate the need for the VOLUME instruction, and override it if they are present. |
| 1349 |
# The mount options used are those typically found on Linux systems. |
| 1350 |
# Of special note is the "exec" option for "/tmp", which is required by ansible-test for path injection of executables using temporary directories. |
| 1351 |
'--tmpfs', '/tmp:exec', |
| 1352 |
'--tmpfs', '/run:exec', |
| 1353 |
'--tmpfs', '/run/lock', # some systemd containers require a separate tmpfs here, such as Ubuntu 20.04 and Ubuntu 22.04 |
| 1354 |
] |
| 1355 |
|
| 1356 |
if self.config.privileged: |
| 1357 |
options.append('--privileged') |
| 1358 |
|
| 1359 |
if self.config.memory: |
| 1360 |
options.extend([ |
| 1361 |
f'--memory={self.config.memory}', |
| 1362 |
f'--memory-swap={self.config.memory}', |
| 1363 |
]) |
| 1364 |
|
| 1365 |
if self.config.seccomp != 'default': |
| 1366 |
options.extend(['--security-opt', f'seccomp={self.config.seccomp}']) |
| 1367 |
|
| 1368 |
return options |
| 1369 |
|
| 1370 |
|
| 1371 |
class NetworkInventoryProfile(HostProfile[NetworkInventoryConfig]): |
| 1372 |
"""Host profile for a network inventory.""" |
| 1373 |
|
| 1374 |
@property |
| 1375 |
def name(self) -> str: |
| 1376 |
"""The name of the host profile.""" |
| 1377 |
return self.config.path |
| 1378 |
|
| 1379 |
|
| 1380 |
class NetworkRemoteProfile(RemoteProfile[NetworkRemoteConfig]): |
| 1381 |
"""Host profile for a network remote instance.""" |
| 1382 |
|
| 1383 |
def wait(self) -> None: |
| 1384 |
"""Wait for the instance to be ready. Executed before delegation for the controller and after delegation for targets.""" |
| 1385 |
self.wait_until_ready() |
| 1386 |
|
| 1387 |
def get_inventory_variables(self) -> dict[str, t.Optional[t.Union[str, int]]]: |
| 1388 |
"""Return inventory variables for accessing this host.""" |
| 1389 |
core_ci = self.wait_for_instance() |
| 1390 |
connection = core_ci.connection |
| 1391 |
|
| 1392 |
variables: dict[str, t.Optional[t.Union[str, int]]] = dict( |
| 1393 |
ansible_connection=self.config.connection, |
| 1394 |
ansible_pipelining='yes', |
| 1395 |
ansible_host=connection.hostname, |
| 1396 |
ansible_port=connection.port, |
| 1397 |
ansible_user=connection.username, |
| 1398 |
ansible_ssh_private_key_file=core_ci.ssh_key.key, |
| 1399 |
# VyOS 1.1.8 uses OpenSSH 5.5, making it incompatible with RSA SHA-256/512 used by Paramiko 2.9 and later. |
| 1400 |
# IOS CSR 1000V uses an ancient SSH server, making it incompatible with RSA SHA-256/512 used by Paramiko 2.9 and later. |
| 1401 |
# That means all network platforms currently offered by ansible-core-ci require support for RSA SHA-1, so it is simply hard-coded here. |
| 1402 |
# NOTE: This option only exists in ansible-core 2.14 and later. For older ansible-core versions, use of Paramiko 2.8.x or earlier is required. |
| 1403 |
# See: https://github.com/ansible/ansible/pull/78789 |
| 1404 |
# See: https://github.com/ansible/ansible/pull/78842 |
| 1405 |
ansible_paramiko_use_rsa_sha2_algorithms='no', |
| 1406 |
ansible_network_os=f'{self.config.collection}.{self.config.platform}' if self.config.collection else self.config.platform, |
| 1407 |
) |
| 1408 |
|
| 1409 |
return variables |
| 1410 |
|
| 1411 |
def wait_until_ready(self) -> None: |
| 1412 |
"""Wait for the host to respond to an Ansible module request.""" |
| 1413 |
core_ci = self.wait_for_instance() |
| 1414 |
|
| 1415 |
if not isinstance(self.args, IntegrationConfig): |
| 1416 |
return # skip extended checks unless we're running integration tests |
| 1417 |
|
| 1418 |
inventory = Inventory.create_single_host(sanitize_host_name(self.config.name), self.get_inventory_variables()) |
| 1419 |
env = ansible_environment(self.args) |
| 1420 |
module_name = f'{self.config.collection + "." if self.config.collection else ""}{self.config.platform}_command' |
| 1421 |
|
| 1422 |
with tempfile.NamedTemporaryFile(suffix='.json') as inventory_file: |
| 1423 |
inventory.write(self.args, inventory_file.name) |
| 1424 |
|
| 1425 |
cmd = ['ansible', '-m', module_name, '-a', 'commands=?', '-i', inventory_file.name, 'all'] |
| 1426 |
|
| 1427 |
for dummy in range(1, 90): |
| 1428 |
try: |
| 1429 |
intercept_python(self.args, self.args.controller_python, cmd, env, capture=True) |
| 1430 |
except SubprocessError as ex: |
| 1431 |
display.warning(str(ex)) |
| 1432 |
time.sleep(10) |
| 1433 |
else: |
| 1434 |
return |
| 1435 |
|
| 1436 |
raise HostConnectionError(f'Timeout waiting for {self.config.name} instance {core_ci.instance_id}.') |
| 1437 |
|
| 1438 |
def get_controller_target_connections(self) -> list[SshConnection]: |
| 1439 |
"""Return SSH connection(s) for accessing the host as a target from the controller.""" |
| 1440 |
core_ci = self.wait_for_instance() |
| 1441 |
|
| 1442 |
settings = SshConnectionDetail( |
| 1443 |
name=core_ci.name, |
| 1444 |
host=core_ci.connection.hostname, |
| 1445 |
port=core_ci.connection.port, |
| 1446 |
user=core_ci.connection.username, |
| 1447 |
identity_file=core_ci.ssh_key.key, |
| 1448 |
# VyOS 1.1.8 uses OpenSSH 5.5, making it incompatible with the default configuration of OpenSSH 8.8 and later clients. |
| 1449 |
# IOS CSR 1000V uses an ancient SSH server, making it incompatible with the default configuration of OpenSSH 8.8 and later clients. |
| 1450 |
# That means all network platforms currently offered by ansible-core-ci require support for RSA SHA-1, so it is simply hard-coded here. |
| 1451 |
enable_rsa_sha1=True, |
| 1452 |
) |
| 1453 |
|
| 1454 |
return [SshConnection(self.args, settings)] |
| 1455 |
|
| 1456 |
|
| 1457 |
class OriginProfile(ControllerHostProfile[OriginConfig]): |
| 1458 |
"""Host profile for origin.""" |
| 1459 |
|
| 1460 |
@property |
| 1461 |
def name(self) -> str: |
| 1462 |
"""The name of the host profile.""" |
| 1463 |
return 'origin' |
| 1464 |
|
| 1465 |
def get_origin_controller_connection(self) -> LocalConnection: |
| 1466 |
"""Return a connection for accessing the host as a controller from the origin.""" |
| 1467 |
return LocalConnection(self.args) |
| 1468 |
|
| 1469 |
def get_working_directory(self) -> str: |
| 1470 |
"""Return the working directory for the host.""" |
| 1471 |
return os.getcwd() |
| 1472 |
|
| 1473 |
|
| 1474 |
class PosixRemoteProfile(ControllerHostProfile[PosixRemoteConfig], RemoteProfile[PosixRemoteConfig], DebuggableProfile[PosixRemoteConfig]): |
| 1475 |
"""Host profile for a POSIX remote instance.""" |
| 1476 |
|
| 1477 |
def wait(self) -> None: |
| 1478 |
"""Wait for the instance to be ready. Executed before delegation for the controller and after delegation for targets.""" |
| 1479 |
self.wait_until_ready() |
| 1480 |
|
| 1481 |
def setup(self) -> None: |
| 1482 |
"""Perform out-of-band setup before delegation.""" |
| 1483 |
if self.debugging_enabled: |
| 1484 |
self.enable_debugger_forwarding(self.get_origin_controller_connection().settings) |
| 1485 |
|
| 1486 |
def configure(self) -> None: |
| 1487 |
"""Perform in-band configuration. Executed before delegation for the controller and after delegation for targets.""" |
| 1488 |
core_ci = self.wait_for_instance() |
| 1489 |
pwd = self.wait_until_ready() |
| 1490 |
|
| 1491 |
display.info(f'Remote working directory: {pwd}', verbosity=1) |
| 1492 |
|
| 1493 |
bootstrapper = BootstrapRemote( |
| 1494 |
controller=self.controller, |
| 1495 |
platform=self.config.platform, |
| 1496 |
platform_version=self.config.version, |
| 1497 |
python_interpreters=self.get_python_interpreters(), |
| 1498 |
powershell_versions=self.get_powershell_versions(), |
| 1499 |
ssh_key=core_ci.ssh_key, |
| 1500 |
) |
| 1501 |
|
| 1502 |
setup_sh = bootstrapper.get_script() |
| 1503 |
shell = setup_sh.splitlines()[0][2:] |
| 1504 |
|
| 1505 |
ssh = self.get_origin_controller_connection() |
| 1506 |
ssh.run([shell], data=setup_sh, capture=False) |
| 1507 |
|
| 1508 |
def get_ssh_connection(self) -> SshConnection: |
| 1509 |
"""Return an SSH connection for accessing the host.""" |
| 1510 |
core_ci = self.wait_for_instance() |
| 1511 |
|
| 1512 |
settings = SshConnectionDetail( |
| 1513 |
name=core_ci.name, |
| 1514 |
user=core_ci.connection.username, |
| 1515 |
host=core_ci.connection.hostname, |
| 1516 |
port=core_ci.connection.port, |
| 1517 |
identity_file=core_ci.ssh_key.key, |
| 1518 |
python_interpreter=self.python.path, |
| 1519 |
powershell_interpreter=self.powershell.path, |
| 1520 |
) |
| 1521 |
|
| 1522 |
if settings.user == 'root': |
| 1523 |
become: t.Optional[Become] = None |
| 1524 |
elif self.config.become: |
| 1525 |
become = SUPPORTED_BECOME_METHODS[self.config.become]() |
| 1526 |
else: |
| 1527 |
display.warning(f'Defaulting to "sudo" for platform "{self.config.platform}" become support.', unique=True) |
| 1528 |
become = Sudo() |
| 1529 |
|
| 1530 |
return SshConnection(self.args, settings, become) |
| 1531 |
|
| 1532 |
def wait_until_ready(self) -> str: |
| 1533 |
"""Wait for instance to respond to SSH, returning the current working directory once connected.""" |
| 1534 |
core_ci = self.wait_for_instance() |
| 1535 |
|
| 1536 |
for dummy in range(1, 90): |
| 1537 |
try: |
| 1538 |
return self.get_working_directory() |
| 1539 |
except SubprocessError as ex: |
| 1540 |
# No "Permission denied" check is performed here. |
| 1541 |
# Unlike containers, with remote instances, user configuration isn't guaranteed to have been completed before SSH connections are attempted. |
| 1542 |
display.warning(str(ex)) |
| 1543 |
time.sleep(10) |
| 1544 |
|
| 1545 |
raise HostConnectionError(f'Timeout waiting for {self.config.name} instance {core_ci.instance_id}.') |
| 1546 |
|
| 1547 |
def get_controller_target_connections(self) -> list[SshConnection]: |
| 1548 |
"""Return SSH connection(s) for accessing the host as a target from the controller.""" |
| 1549 |
return [self.get_ssh_connection()] |
| 1550 |
|
| 1551 |
def get_origin_controller_connection(self) -> SshConnection: |
| 1552 |
"""Return a connection for accessing the host as a controller from the origin.""" |
| 1553 |
return self.get_ssh_connection() |
| 1554 |
|
| 1555 |
def get_working_directory(self) -> str: |
| 1556 |
"""Return the working directory for the host.""" |
| 1557 |
if not self.pwd: |
| 1558 |
ssh = self.get_origin_controller_connection() |
| 1559 |
stdout = ssh.run(['pwd'], capture=True)[0] |
| 1560 |
|
| 1561 |
if self.args.explain: |
| 1562 |
return '/pwd' |
| 1563 |
|
| 1564 |
pwd = stdout.strip().splitlines()[-1] |
| 1565 |
|
| 1566 |
if not pwd.startswith('/'): |
| 1567 |
raise Exception(f'Unexpected current working directory "{pwd}" from "pwd" command output:\n{stdout.strip()}') |
| 1568 |
|
| 1569 |
self.pwd = pwd |
| 1570 |
|
| 1571 |
return self.pwd |
| 1572 |
|
| 1573 |
@property |
| 1574 |
def pwd(self) -> t.Optional[str]: |
| 1575 |
"""Return the cached pwd, if any, otherwise None.""" |
| 1576 |
return self.cache.get('pwd') |
| 1577 |
|
| 1578 |
@pwd.setter |
| 1579 |
def pwd(self, value: str) -> None: |
| 1580 |
"""Cache the given pwd.""" |
| 1581 |
self.cache['pwd'] = value |
| 1582 |
|
| 1583 |
|
| 1584 |
class PosixSshProfile(SshTargetHostProfile[PosixSshConfig], PosixProfile[PosixSshConfig]): |
| 1585 |
"""Host profile for a POSIX SSH instance.""" |
| 1586 |
|
| 1587 |
@property |
| 1588 |
def name(self) -> str: |
| 1589 |
"""The name of the host profile.""" |
| 1590 |
return self.config.host |
| 1591 |
|
| 1592 |
def get_controller_target_connections(self) -> list[SshConnection]: |
| 1593 |
"""Return SSH connection(s) for accessing the host as a target from the controller.""" |
| 1594 |
settings = SshConnectionDetail( |
| 1595 |
name='target', |
| 1596 |
user=self.config.user, |
| 1597 |
host=self.config.host, |
| 1598 |
port=self.config.port, |
| 1599 |
identity_file=SshKey(self.args).key, |
| 1600 |
python_interpreter=self.python.path, |
| 1601 |
powershell_interpreter=self.powershell.path, |
| 1602 |
) |
| 1603 |
|
| 1604 |
return [SshConnection(self.args, settings)] |
| 1605 |
|
| 1606 |
|
| 1607 |
class WindowsInventoryProfile(SshTargetHostProfile[WindowsInventoryConfig]): |
| 1608 |
"""Host profile for a Windows inventory.""" |
| 1609 |
|
| 1610 |
@property |
| 1611 |
def name(self) -> str: |
| 1612 |
"""The name of the host profile.""" |
| 1613 |
return self.config.path |
| 1614 |
|
| 1615 |
def get_controller_target_connections(self) -> list[SshConnection]: |
| 1616 |
"""Return SSH connection(s) for accessing the host as a target from the controller.""" |
| 1617 |
inventory = parse_inventory(self.args, self.config.path) |
| 1618 |
hosts = get_hosts(inventory, 'windows') |
| 1619 |
identity_file = SshKey(self.args).key |
| 1620 |
|
| 1621 |
settings = [SshConnectionDetail( |
| 1622 |
name=name, |
| 1623 |
host=config['ansible_host'], |
| 1624 |
port=22, |
| 1625 |
user=config['ansible_user'], |
| 1626 |
identity_file=identity_file, |
| 1627 |
shell_type='powershell', |
| 1628 |
) for name, config in hosts.items()] |
| 1629 |
|
| 1630 |
if settings: |
| 1631 |
details = '\n'.join(f'{ssh.name} {ssh.user}@{ssh.host}:{ssh.port}' for ssh in settings) |
| 1632 |
display.info(f'Generated SSH connection details from inventory:\n{details}', verbosity=1) |
| 1633 |
|
| 1634 |
return [SshConnection(self.args, setting) for setting in settings] |
| 1635 |
|
| 1636 |
|
| 1637 |
class WindowsRemoteProfile(RemoteProfile[WindowsRemoteConfig]): |
| 1638 |
"""Host profile for a Windows remote instance.""" |
| 1639 |
|
| 1640 |
_ARCHES = { |
| 1641 |
Architecture.X86_64: 'x64', |
| 1642 |
Architecture.AARCH64: 'arm64', |
| 1643 |
} |
| 1644 |
"""Mapping of ansible-test architecture to PowerShell release architecture label.""" |
| 1645 |
|
| 1646 |
def __init__(self, **kwargs) -> None: |
| 1647 |
super().__init__(**kwargs) |
| 1648 |
|
| 1649 |
self.pwsh_interpreter_path: str | None = None |
| 1650 |
|
| 1651 |
def wait(self) -> None: |
| 1652 |
"""Wait for the instance to be ready. Executed before delegation for the controller and after delegation for targets.""" |
| 1653 |
self.wait_until_ready() |
| 1654 |
|
| 1655 |
def configure(self) -> None: |
| 1656 |
"""Perform in-band configuration. Executed before delegation for the controller and after delegation for targets.""" |
| 1657 |
if not self.config.powershell: # nothing to install |
| 1658 |
return |
| 1659 |
|
| 1660 |
if self.config.powershell.version == '5.1': # built-in version, nothing to install |
| 1661 |
return |
| 1662 |
|
| 1663 |
self.wait_for_instance() |
| 1664 |
self.wait_until_ready() |
| 1665 |
|
| 1666 |
full_version = get_powershell_version_map()[self.config.powershell.version] |
| 1667 |
arch = self._ARCHES[self.config.arch] |
| 1668 |
download_uri = f'https://github.com/PowerShell/PowerShell/releases/download/v{full_version}/PowerShell-{full_version}-win-{arch}.zip' |
| 1669 |
setup_path = pathlib.Path(ANSIBLE_TEST_TARGET_ROOT) / 'setup' |
| 1670 |
bootstrap_script_path = setup_path / 'bootstrap.ps1' |
| 1671 |
entrypoint_script_path = setup_path / 'entrypoint.ps1' |
| 1672 |
|
| 1673 |
setup_manifest = dict( |
| 1674 |
script=bootstrap_script_path.read_text(), |
| 1675 |
path=str(bootstrap_script_path.resolve()), |
| 1676 |
params=dict( |
| 1677 |
PowerShellVersion=self.config.powershell.version, |
| 1678 |
PowerShellDownloadUri=download_uri, |
| 1679 |
), |
| 1680 |
) |
| 1681 |
|
| 1682 |
encoded_manifest = base64.b64encode(json.dumps(setup_manifest).encode()).decode() |
| 1683 |
|
| 1684 |
# Passing a command through stdin requires newlines at the end of the input |
| 1685 |
# so it sees it as a complete statement rather than ignoring an incomplete one. |
| 1686 |
setup_entrypoint = entrypoint_script_path.read_text().replace('{{ MANIFEST }}', encoded_manifest).strip() + "\n\n" |
| 1687 |
|
| 1688 |
ssh = self.get_controller_target_connections()[0] |
| 1689 |
|
| 1690 |
stdout, dummy = ssh.run( |
| 1691 |
command=['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', '-'], |
| 1692 |
data=setup_entrypoint, |
| 1693 |
capture=True, |
| 1694 |
) |
| 1695 |
|
| 1696 |
self.pwsh_interpreter_path = stdout.strip() |
| 1697 |
|
| 1698 |
def get_inventory_variables(self) -> dict[str, t.Optional[t.Union[str, int]]]: |
| 1699 |
"""Return inventory variables for accessing this host.""" |
| 1700 |
core_ci = self.wait_for_instance() |
| 1701 |
connection = core_ci.connection |
| 1702 |
|
| 1703 |
variables: dict[str, t.Optional[t.Union[str, int]]] = dict( |
| 1704 |
ansible_host=connection.hostname, |
| 1705 |
# ansible_port is intentionally not set using connection.port -- connection-specific variables can set this instead |
| 1706 |
ansible_user=connection.username, |
| 1707 |
ansible_ssh_private_key_file=core_ci.ssh_key.key, # required for scenarios which change the connection plugin to SSH |
| 1708 |
ansible_test_connection_password=connection.password, # required for scenarios which change the connection plugin to require a password |
| 1709 |
) |
| 1710 |
|
| 1711 |
variables.update(ansible_connection=self.config.connection.split('+')[0]) |
| 1712 |
variables.update(WINDOWS_CONNECTION_VARIABLES[self.config.connection]) |
| 1713 |
|
| 1714 |
if self.pwsh_interpreter_path: |
| 1715 |
variables.update(ansible_pwsh_interpreter=self.pwsh_interpreter_path) |
| 1716 |
|
| 1717 |
if variables.pop('use_password'): |
| 1718 |
variables.update(ansible_password=connection.password) |
| 1719 |
|
| 1720 |
return variables |
| 1721 |
|
| 1722 |
def wait_until_ready(self) -> None: |
| 1723 |
"""Wait for the host to respond to an Ansible module request.""" |
| 1724 |
core_ci = self.wait_for_instance() |
| 1725 |
|
| 1726 |
if not isinstance(self.args, IntegrationConfig): |
| 1727 |
return # skip extended checks unless we're running integration tests |
| 1728 |
|
| 1729 |
inventory = Inventory.create_single_host(sanitize_host_name(self.config.name), self.get_inventory_variables()) |
| 1730 |
env = ansible_environment(self.args) |
| 1731 |
module_name = 'ansible.windows.win_ping' |
| 1732 |
|
| 1733 |
with tempfile.NamedTemporaryFile(suffix='.json') as inventory_file: |
| 1734 |
inventory.write(self.args, inventory_file.name) |
| 1735 |
|
| 1736 |
cmd = ['ansible', '-m', module_name, '-i', inventory_file.name, 'all'] |
| 1737 |
|
| 1738 |
for dummy in range(1, 120): |
| 1739 |
try: |
| 1740 |
intercept_python(self.args, self.args.controller_python, cmd, env, capture=True) |
| 1741 |
except SubprocessError as ex: |
| 1742 |
display.warning(str(ex)) |
| 1743 |
time.sleep(10) |
| 1744 |
else: |
| 1745 |
return |
| 1746 |
|
| 1747 |
raise HostConnectionError(f'Timeout waiting for {self.config.name} instance {core_ci.instance_id}.') |
| 1748 |
|
| 1749 |
def get_controller_target_connections(self) -> list[SshConnection]: |
| 1750 |
"""Return SSH connection(s) for accessing the host as a target from the controller.""" |
| 1751 |
core_ci = self.wait_for_instance() |
| 1752 |
|
| 1753 |
settings = SshConnectionDetail( |
| 1754 |
name=core_ci.name, |
| 1755 |
host=core_ci.connection.hostname, |
| 1756 |
port=22, |
| 1757 |
user=core_ci.connection.username, |
| 1758 |
identity_file=core_ci.ssh_key.key, |
| 1759 |
shell_type='powershell', |
| 1760 |
) |
| 1761 |
|
| 1762 |
return [SshConnection(self.args, settings)] |
| 1763 |
|
| 1764 |
|
| 1765 |
@cache |
| 1766 |
def get_config_profile_type_map() -> dict[t.Type[HostConfig], t.Type[HostProfile]]: |
| 1767 |
"""Create and return a mapping of HostConfig types to HostProfile types.""" |
| 1768 |
return get_type_map(HostProfile, HostConfig) |
| 1769 |
|
| 1770 |
|
| 1771 |
def create_host_profile( |
| 1772 |
args: EnvironmentConfig, |
| 1773 |
config: HostConfig, |
| 1774 |
controller: ControllerHostProfile | None, |
| 1775 |
) -> HostProfile: |
| 1776 |
"""Create and return a host profile from the given host configuration.""" |
| 1777 |
profile_type = get_config_profile_type_map()[type(config)] |
| 1778 |
profile = profile_type(args=args, config=config, controller=controller) |
| 1779 |
return profile |