Debian Codegraph @

test/lib/ansible_test/_internal/containers.py

raw
1 """High level functions for working with containers."""
2
3 from __future__ import annotations
4
5 import collections.abc as c
6 import contextlib
7 import json
8 import random
9 import time
10 import uuid
11 import threading
12 import typing as t
13
14 from .util import (
15 ApplicationError,
16 SubprocessError,
17 display,
18 sanitize_host_name,
19 )
20
21 from .util_common import (
22 ExitHandler,
23 named_temporary_file,
24 )
25
26 from .config import (
27 EnvironmentConfig,
28 IntegrationConfig,
29 SanityConfig,
30 ShellConfig,
31 UnitsConfig,
32 WindowsIntegrationConfig,
33 )
34
35 from .docker_util import (
36 ContainerNotFoundError,
37 DockerInspect,
38 docker_create,
39 docker_exec,
40 docker_inspect,
41 docker_network_inspect,
42 docker_pull,
43 docker_rm,
44 docker_run,
45 docker_start,
46 get_docker_container_id,
47 get_docker_host_ip,
48 get_podman_host_ip,
49 get_session_container_name,
50 require_docker,
51 detect_host_properties,
52 )
53
54 from .ansible_util import (
55 run_playbook,
56 )
57
58 from .core_ci import (
59 SshKey,
60 )
61
62 from .target import (
63 IntegrationTarget,
64 )
65
66 from .ssh import (
67 SshConnectionDetail,
68 SshProcess,
69 create_ssh_port_forwards,
70 create_ssh_port_redirects,
71 generate_ssh_inventory,
72 )
73
74 from .host_configs import (
75 ControllerConfig,
76 DockerConfig,
77 OriginConfig,
78 PosixSshConfig,
79 PythonConfig,
80 RemoteConfig,
81 WindowsInventoryConfig,
82 )
83
84 from .connections import (
85 SshConnection,
86 )
87
88 from .thread import (
89 mutex,
90 )
91
92 # information about support containers provisioned by the current ansible-test instance
93 support_containers: dict[str, ContainerDescriptor] = {}
94 support_containers_mutex = threading.Lock()
95
96
97 class HostType:
98 """Enum representing the types of hosts involved in running tests."""
99
100 origin = 'origin'
101 control = 'control'
102 managed = 'managed'
103
104
105 def run_support_container(
106 args: EnvironmentConfig,
107 context: str,
108 image: str,
109 name: str,
110 ports: list[int],
111 aliases: t.Optional[list[str]] = None,
112 start: bool = True,
113 cleanup: bool = True,
114 cmd: t.Optional[list[str]] = None,
115 env: t.Optional[dict[str, str]] = None,
116 options: t.Optional[list[str]] = None,
117 publish_ports: bool = True,
118 data_container: bool = False,
119 ) -> t.Optional[ContainerDescriptor]:
120 """
121 Start a container used to support tests, but not run them.
122 Containers created this way will be accessible from tests.
123 """
124 name = get_session_container_name(args, name)
125
126 if args.prime_containers:
127 docker_pull(args, image)
128 return None
129
130 # SSH is required for publishing ports, as well as modifying the hosts file.
131 # Initializing the SSH key here makes sure it is available for use after delegation.
132 SshKey(args)
133
134 aliases = aliases or [sanitize_host_name(name)]
135
136 docker_command = require_docker().command
137 current_container_id = get_docker_container_id()
138
139 if docker_command == 'docker':
140 if isinstance(args.controller, DockerConfig) and all(isinstance(target, (ControllerConfig, DockerConfig)) for target in args.targets):
141 publish_ports = False # publishing ports is not needed when test hosts are on the docker network
142
143 if current_container_id:
144 publish_ports = False # publishing ports is pointless if already running in a docker container
145
146 options = options or []
147
148 if start:
149 options.append('-dt') # the -t option is required to cause systemd in the container to log output to the console
150
151 if publish_ports:
152 for port in ports:
153 options.extend(['-p', str(port)])
154
155 if env:
156 for key, value in env.items():
157 options.extend(['--env', '%s=%s' % (key, value)])
158
159 max_open_files = detect_host_properties(args).max_open_files
160
161 options.extend(['--ulimit', 'nofile=%s' % max_open_files])
162
163 if args.dev_systemd_debug:
164 options.extend(('--env', 'SYSTEMD_LOG_LEVEL=debug'))
165
166 display.info('Starting new "%s" container.' % name)
167 docker_pull(args, image)
168 support_container_id = run_container(args, image, name, options, create_only=not start, cmd=cmd)
169 running = start
170
171 descriptor = ContainerDescriptor(
172 image,
173 context,
174 name,
175 support_container_id,
176 ports,
177 aliases,
178 publish_ports,
179 running,
180 cleanup,
181 env,
182 data_container,
183 )
184
185 with support_containers_mutex:
186 if name in support_containers:
187 raise Exception(f'Container already defined: {name}')
188
189 if not support_containers:
190 ExitHandler.register(cleanup_containers, args)
191
192 support_containers[name] = descriptor
193
194 display.info(f'Adding "{name}" to container database.')
195
196 if start:
197 descriptor.register(args)
198
199 return descriptor
200
201
202 def run_container(
203 args: EnvironmentConfig,
204 image: str,
205 name: str,
206 options: t.Optional[list[str]],
207 cmd: t.Optional[list[str]] = None,
208 create_only: bool = False,
209 ) -> str:
210 """Run a container using the given docker image."""
211 options = list(options or [])
212 cmd = list(cmd or [])
213
214 options.extend(['--name', name])
215
216 network = get_docker_preferred_network_name(args)
217
218 if is_docker_user_defined_network(network):
219 # Only when the network is not the default bridge network.
220 options.extend(['--network', network])
221
222 for _iteration in range(1, 3):
223 try:
224 if create_only:
225 stdout = docker_create(args, image, options, cmd)[0]
226 else:
227 stdout = docker_run(args, image, options, cmd)[0]
228 except SubprocessError as ex:
229 display.error(ex.message)
230 display.warning(f'Failed to run docker image "{image}". Waiting a few seconds before trying again.')
231 docker_rm(args, name) # podman doesn't remove containers after create if run fails
232 time.sleep(3)
233 else:
234 if args.explain:
235 stdout = ''.join(random.choice('0123456789abcdef') for _iteration in range(64))
236
237 return stdout.strip()
238
239 raise ApplicationError(f'Failed to run docker image "{image}".')
240
241
242 def start_container(args: EnvironmentConfig, container_id: str) -> tuple[t.Optional[str], t.Optional[str]]:
243 """Start a docker container by name or ID."""
244 options: list[str] = []
245
246 for _iteration in range(1, 3):
247 try:
248 return docker_start(args, container_id, options)
249 except SubprocessError as ex:
250 display.error(ex.message)
251 display.warning(f'Failed to start docker container "{container_id}". Waiting a few seconds before trying again.')
252 time.sleep(3)
253
254 raise ApplicationError(f'Failed to start docker container "{container_id}".')
255
256
257 def get_container_ip_address(args: EnvironmentConfig, container: DockerInspect) -> t.Optional[str]:
258 """Return the IP address of the container for the preferred docker network."""
259 if container.networks:
260 network_name = get_docker_preferred_network_name(args)
261
262 if not network_name:
263 # Sort networks and use the first available.
264 # This assumes all containers will have access to the same networks.
265 network_name = sorted(container.networks.keys()).pop(0)
266
267 ipaddress = container.networks[network_name]['IPAddress']
268 else:
269 ipaddress = container.network_settings['IPAddress']
270
271 if not ipaddress:
272 return None
273
274 return ipaddress
275
276
277 @mutex
278 def get_docker_preferred_network_name(args: EnvironmentConfig) -> t.Optional[str]:
279 """
280 Return the preferred network name for use with Docker. The selection logic is:
281 - the network selected by the user with `--docker-network`
282 - the network of the currently running docker container (if any)
283 - the default docker network (returns None)
284 """
285 try:
286 return get_docker_preferred_network_name.network # type: ignore[attr-defined]
287 except AttributeError:
288 pass
289
290 network = None
291
292 if args.docker_network:
293 network = args.docker_network
294 else:
295 current_container_id = get_docker_container_id()
296
297 if current_container_id:
298 try:
299 # Make sure any additional containers we launch use the same network as the current container we're running in.
300 # This is needed when ansible-test is running in a container that is not connected to Docker's default network.
301 container = docker_inspect(args, current_container_id, always=True)
302 network = container.get_network_name()
303 except ContainerNotFoundError:
304 display.warning('Unable to detect the network for the current container. Use the `--docker-network` option if containers are unreachable.')
305
306 # The default docker behavior puts containers on the same network.
307 # The default podman behavior puts containers on isolated networks which don't allow communication between containers or network disconnect.
308 # Starting with podman version 2.1.0 rootless containers are able to join networks.
309 # Starting with podman version 2.2.0 containers can be disconnected from networks.
310 # To maintain feature parity with docker, detect and use the default "podman" network when running under podman.
311 if network is None and require_docker().command == 'podman' and docker_network_inspect(args, 'podman', always=True):
312 network = 'podman'
313
314 get_docker_preferred_network_name.network = network # type: ignore[attr-defined]
315
316 return network
317
318
319 def is_docker_user_defined_network(network: str) -> bool:
320 """Return True if the network being used is a user-defined network."""
321 return bool(network) and network != 'bridge'
322
323
324 @mutex
325 def get_container_database(args: EnvironmentConfig) -> ContainerDatabase:
326 """Return the current container database, creating it as needed, or returning the one provided on the command line through delegation."""
327 try:
328 return get_container_database.database # type: ignore[attr-defined]
329 except AttributeError:
330 pass
331
332 if args.containers:
333 display.info('Parsing container database.', verbosity=1)
334 database = ContainerDatabase.from_dict(json.loads(args.containers))
335 else:
336 display.info('Creating container database.', verbosity=1)
337 database = create_container_database(args)
338
339 display.info('>>> Container Database\n%s' % json.dumps(database.to_dict(), indent=4, sort_keys=True), verbosity=3)
340
341 get_container_database.database = database # type: ignore[attr-defined]
342
343 return database
344
345
346 class ContainerAccess:
347 """Information needed for one test host to access a single container supporting tests."""
348
349 def __init__(self, host_ip: str, names: list[str], ports: t.Optional[list[int]], forwards: t.Optional[dict[int, int]]) -> None:
350 # if forwards is set
351 # this is where forwards are sent (it is the host that provides an indirect connection to the containers on alternate ports)
352 # /etc/hosts uses 127.0.0.1 (since port redirection will be used)
353 # else
354 # this is what goes into /etc/hosts (it is the container's direct IP)
355 self.host_ip = host_ip
356
357 # primary name + any aliases -- these go into the hosts file and reference the appropriate ip for the origin/control/managed host
358 self.names = names
359
360 # ports available (set if forwards is not set)
361 self.ports = ports
362
363 # port redirections to create through host_ip -- if not set, no port redirections will be used
364 self.forwards = forwards
365
366 def port_map(self) -> list[tuple[int, int]]:
367 """Return a port map for accessing this container."""
368 if self.forwards:
369 ports = list(self.forwards.items())
370 else:
371 ports = [(port, port) for port in self.ports or []]
372
373 return ports
374
375 @staticmethod
376 def from_dict(data: dict[str, t.Any]) -> ContainerAccess:
377 """Return a ContainerAccess instance from the given dict."""
378 forwards = data.get('forwards')
379
380 if forwards:
381 forwards = dict((int(key), value) for key, value in forwards.items())
382
383 return ContainerAccess(
384 host_ip=data['host_ip'],
385 names=data['names'],
386 ports=data.get('ports'),
387 forwards=forwards,
388 )
389
390 def to_dict(self) -> dict[str, t.Any]:
391 """Return a dict of the current instance."""
392 value: dict[str, t.Any] = dict(
393 host_ip=self.host_ip,
394 names=self.names,
395 )
396
397 if self.ports:
398 value.update(ports=self.ports)
399
400 if self.forwards:
401 value.update(forwards=self.forwards)
402
403 return value
404
405
406 class ContainerDatabase:
407 """Database of running containers used to support tests."""
408
409 def __init__(self, data: dict[str, dict[str, dict[str, ContainerAccess]]]) -> None:
410 self.data = data
411
412 @staticmethod
413 def from_dict(data: dict[str, t.Any]) -> ContainerDatabase:
414 """Return a ContainerDatabase instance from the given dict."""
415 return ContainerDatabase(dict((access_name,
416 dict((context_name,
417 dict((container_name, ContainerAccess.from_dict(container))
418 for container_name, container in containers.items()))
419 for context_name, containers in contexts.items()))
420 for access_name, contexts in data.items()))
421
422 def to_dict(self) -> dict[str, t.Any]:
423 """Return a dict of the current instance."""
424 return dict((access_name,
425 dict((context_name,
426 dict((container_name, container.to_dict())
427 for container_name, container in containers.items()))
428 for context_name, containers in contexts.items()))
429 for access_name, contexts in self.data.items())
430
431
432 def local_ssh(args: EnvironmentConfig, python: PythonConfig) -> SshConnectionDetail:
433 """Return SSH connection details for localhost, connecting as root to the default SSH port."""
434 return SshConnectionDetail('localhost', 'localhost', None, 'root', SshKey(args).key, python.path)
435
436
437 def root_ssh(ssh: SshConnection) -> SshConnectionDetail:
438 """Return the SSH connection details from the given SSH connection. If become was specified, the user will be changed to `root`."""
439 settings = ssh.settings.__dict__.copy()
440
441 if ssh.become:
442 settings.update(
443 user='root',
444 )
445
446 return SshConnectionDetail(**settings)
447
448
449 def create_container_database(args: EnvironmentConfig) -> ContainerDatabase:
450 """Create and return a container database with information necessary for all test hosts to make use of relevant support containers."""
451 origin: dict[str, dict[str, ContainerAccess]] = {}
452 control: dict[str, dict[str, ContainerAccess]] = {}
453 managed: dict[str, dict[str, ContainerAccess]] = {}
454
455 for name, container in support_containers.items():
456 if container.data_container:
457 # data containers will not be started, and will be missing details
458 continue
459 if container.details.published_ports:
460 if require_docker().command == 'podman':
461 host_ip_func = get_podman_host_ip
462 else:
463 host_ip_func = get_docker_host_ip
464 published_access = ContainerAccess(
465 host_ip=host_ip_func(),
466 names=container.aliases,
467 ports=None,
468 forwards=dict((port, published_port) for port, published_port in container.details.published_ports.items()),
469 )
470 else:
471 published_access = None # no published access without published ports (ports are only published if needed)
472
473 if container.details.container_ip:
474 # docker containers, and rootfull podman containers should have a container IP address
475 container_access = ContainerAccess(
476 host_ip=container.details.container_ip,
477 names=container.aliases,
478 ports=container.ports,
479 forwards=None,
480 )
481 elif require_docker().command == 'podman':
482 # published ports for rootless podman containers should be accessible from the host's IP
483 container_access = ContainerAccess(
484 host_ip=get_podman_host_ip(),
485 names=container.aliases,
486 ports=None,
487 forwards=dict((port, published_port) for port, published_port in container.details.published_ports.items()),
488 )
489 else:
490 container_access = None # no container access without an IP address
491
492 if get_docker_container_id():
493 if not container_access:
494 raise Exception('Missing IP address for container: %s' % name)
495
496 origin_context = origin.setdefault(container.context, {})
497 origin_context[name] = container_access
498 elif not published_access:
499 pass # origin does not have network access to the containers
500 else:
501 origin_context = origin.setdefault(container.context, {})
502 origin_context[name] = published_access
503
504 if isinstance(args.controller, RemoteConfig):
505 pass # SSH forwarding required
506 elif '-controller-' in name:
507 pass # hack to avoid exposing the controller container to the controller
508 elif isinstance(args.controller, DockerConfig) or (isinstance(args.controller, OriginConfig) and get_docker_container_id()):
509 if container_access:
510 control_context = control.setdefault(container.context, {})
511 control_context[name] = container_access
512 else:
513 raise Exception('Missing IP address for container: %s' % name)
514 else:
515 if not published_access:
516 raise Exception('Missing published ports for container: %s' % name)
517
518 control_context = control.setdefault(container.context, {})
519 control_context[name] = published_access
520
521 if issubclass(args.target_type, (RemoteConfig, WindowsInventoryConfig, PosixSshConfig)):
522 pass # SSH forwarding required
523 elif '-controller-' in name or '-target-' in name:
524 pass # hack to avoid exposing the controller and target containers to the target
525 elif issubclass(args.target_type, DockerConfig) or (issubclass(args.target_type, OriginConfig) and get_docker_container_id()):
526 if container_access:
527 managed_context = managed.setdefault(container.context, {})
528 managed_context[name] = container_access
529 else:
530 raise Exception('Missing IP address for container: %s' % name)
531 else:
532 if not published_access:
533 raise Exception('Missing published ports for container: %s' % name)
534
535 managed_context = managed.setdefault(container.context, {})
536 managed_context[name] = published_access
537
538 data = {
539 HostType.origin: origin,
540 HostType.control: control,
541 HostType.managed: managed,
542 }
543
544 data = dict((key, value) for key, value in data.items() if value)
545
546 return ContainerDatabase(data)
547
548
549 class SupportContainerContext:
550 """Context object for tracking information relating to access of support containers."""
551
552 def __init__(self, containers: ContainerDatabase, process: t.Optional[SshProcess]) -> None:
553 self.containers = containers
554 self.process = process
555
556 def close(self) -> None:
557 """Close the process maintaining the port forwards."""
558 if not self.process:
559 return # forwarding not in use
560
561 self.process.terminate()
562
563 display.info('Waiting for the session SSH port forwarding process to terminate.', verbosity=1)
564
565 self.process.wait()
566
567
568 @contextlib.contextmanager
569 def support_container_context(
570 args: EnvironmentConfig,
571 ssh: t.Optional[SshConnectionDetail],
572 ) -> c.Iterator[t.Optional[ContainerDatabase]]:
573 """Create a context manager for integration tests that use support containers."""
574 if not isinstance(args, (IntegrationConfig, UnitsConfig, SanityConfig, ShellConfig)):
575 yield None # containers are only needed for commands that have targets (hosts or pythons)
576 return
577
578 containers = get_container_database(args)
579
580 if not containers.data:
581 yield ContainerDatabase({}) # no containers are being used, return an empty database
582 return
583
584 context = create_support_container_context(args, ssh, containers)
585
586 try:
587 yield context.containers
588 finally:
589 context.close()
590
591
592 def create_support_container_context(
593 args: EnvironmentConfig,
594 ssh: t.Optional[SshConnectionDetail],
595 containers: ContainerDatabase,
596 ) -> SupportContainerContext:
597 """Context manager that provides SSH port forwards. Returns updated container metadata."""
598 host_type = HostType.control
599
600 revised = ContainerDatabase(containers.data.copy())
601 source = revised.data.pop(HostType.origin, None)
602
603 container_map: dict[tuple[str, int], tuple[str, str, int]] = {}
604
605 if host_type not in revised.data:
606 if not source:
607 raise Exception('Missing origin container details.')
608
609 for context_name, context in source.items():
610 for container_name, container in context.items():
611 if '-controller-' in container_name:
612 continue # hack to avoid exposing the controller container to the controller
613
614 for port, access_port in container.port_map():
615 container_map[(container.host_ip, access_port)] = (context_name, container_name, port)
616
617 if not container_map:
618 return SupportContainerContext(revised, None)
619
620 if not ssh:
621 raise Exception('The %s host was not pre-configured for container access and SSH forwarding is not available.' % host_type)
622
623 forwards = list(container_map.keys())
624 process = create_ssh_port_forwards(args, ssh, forwards)
625 result = SupportContainerContext(revised, process)
626
627 try:
628 port_forwards = process.collect_port_forwards()
629 contexts: dict[str, dict[str, ContainerAccess]] = {}
630
631 for forward, forwarded_port in port_forwards.items():
632 access_host, access_port = forward
633 context_name, container_name, container_port = container_map[(access_host, access_port)]
634 container = source[context_name][container_name]
635 context = contexts.setdefault(context_name, {})
636
637 forwarded_container = context.setdefault(container_name, ContainerAccess('127.0.0.1', container.names, None, {}))
638 forwarded_container.forwards[container_port] = forwarded_port
639
640 display.info('Container "%s" port %d available at %s:%d is forwarded over SSH as port %d.' % (
641 container_name, container_port, access_host, access_port, forwarded_port,
642 ), verbosity=1)
643
644 revised.data[host_type] = contexts
645
646 return result
647 except Exception:
648 result.close()
649 raise
650
651
652 class ContainerDescriptor:
653 """Information about a support container."""
654
655 def __init__(
656 self,
657 image: str,
658 context: str,
659 name: str,
660 container_id: str,
661 ports: list[int],
662 aliases: list[str],
663 publish_ports: bool,
664 running: bool,
665 cleanup: bool,
666 env: t.Optional[dict[str, str]],
667 data_container: bool,
668 ) -> None:
669 self.image = image
670 self.context = context
671 self.name = name
672 self.container_id = container_id
673 self.ports = ports
674 self.aliases = aliases
675 self.publish_ports = publish_ports
676 self.running = running
677 self.cleanup = cleanup
678 self.env = env
679 self.details: t.Optional[SupportContainer] = None
680 self.data_container = data_container
681
682 def start(self, args: EnvironmentConfig) -> None:
683 """Start the container. Used for containers which are created, but not started."""
684 start_container(args, self.name)
685
686 self.register(args)
687
688 def register(self, args: EnvironmentConfig) -> SupportContainer:
689 """Record the container's runtime details. Must be used after the container has been started."""
690 if self.details:
691 raise Exception('Container already registered: %s' % self.name)
692
693 try:
694 container = docker_inspect(args, self.name)
695 except ContainerNotFoundError:
696 if not args.explain:
697 raise
698
699 # provide enough mock data to keep --explain working
700 container = DockerInspect(args, dict(
701 Id=self.container_id,
702 NetworkSettings=dict(
703 IPAddress='127.0.0.1',
704 Ports=dict(('%d/tcp' % port, [dict(HostPort=random.randint(30000, 40000) if self.publish_ports else port)]) for port in self.ports),
705 ),
706 Config=dict(
707 Env=['%s=%s' % (key, value) for key, value in self.env.items()] if self.env else [],
708 ),
709 ))
710
711 support_container_ip = get_container_ip_address(args, container)
712
713 if self.publish_ports:
714 # inspect the support container to locate the published ports
715 tcp_ports = dict((port, container.get_tcp_port(port)) for port in self.ports)
716
717 if any(not config or len(set(conf['HostPort'] for conf in config)) != 1 for config in tcp_ports.values()):
718 raise ApplicationError('Unexpected `docker inspect` results for published TCP ports:\n%s' % json.dumps(tcp_ports, indent=4, sort_keys=True))
719
720 published_ports = dict((port, int(config[0]['HostPort'])) for port, config in tcp_ports.items())
721 else:
722 published_ports = {}
723
724 self.details = SupportContainer(
725 container,
726 support_container_ip,
727 published_ports,
728 )
729
730 return self.details
731
732
733 class SupportContainer:
734 """Information about a running support container available for use by tests."""
735
736 def __init__(
737 self,
738 container: DockerInspect,
739 container_ip: str,
740 published_ports: dict[int, int],
741 ) -> None:
742 self.container = container
743 self.container_ip = container_ip
744 self.published_ports = published_ports
745
746
747 def wait_for_file(
748 args: EnvironmentConfig,
749 container_name: str,
750 path: str,
751 sleep: int,
752 tries: int,
753 check: t.Optional[c.Callable[[str], bool]] = None,
754 ) -> str:
755 """Wait for the specified file to become available in the requested container and return its contents."""
756 display.info('Waiting for container "%s" to provide file: %s' % (container_name, path))
757
758 for _iteration in range(1, tries):
759 if _iteration > 1:
760 time.sleep(sleep)
761
762 try:
763 stdout = docker_exec(args, container_name, ['dd', 'if=%s' % path], capture=True)[0]
764 except SubprocessError:
765 continue
766
767 if not check or check(stdout):
768 return stdout
769
770 raise ApplicationError('Timeout waiting for container "%s" to provide file: %s' % (container_name, path))
771
772
773 def cleanup_containers(args: EnvironmentConfig) -> None:
774 """Clean up containers."""
775 for container in support_containers.values():
776 if container.cleanup:
777 docker_rm(args, container.name)
778
779
780 def create_hosts_entries(context: dict[str, ContainerAccess]) -> list[str]:
781 """Return hosts entries for the specified context."""
782 entries = []
783 unique_id = uuid.uuid4()
784
785 for container in context.values():
786 # forwards require port redirection through localhost
787 if container.forwards:
788 host_ip = '127.0.0.1'
789 else:
790 host_ip = container.host_ip
791
792 entries.append('%s %s # ansible-test %s' % (host_ip, ' '.join(container.names), unique_id))
793
794 return entries
795
796
797 def create_container_hooks(
798 args: IntegrationConfig,
799 control_connections: list[SshConnectionDetail],
800 managed_connections: t.Optional[list[SshConnectionDetail]],
801 ) -> tuple[t.Optional[c.Callable[[IntegrationTarget], None]], t.Optional[c.Callable[[IntegrationTarget], None]]]:
802 """Return pre and post target callbacks for enabling and disabling container access for each test target."""
803 containers = get_container_database(args)
804
805 control_contexts = containers.data.get(HostType.control)
806
807 if control_contexts:
808 managed_contexts = containers.data.get(HostType.managed)
809
810 if not managed_contexts:
811 managed_contexts = create_managed_contexts(control_contexts)
812
813 control_type = 'posix'
814
815 if isinstance(args, WindowsIntegrationConfig):
816 managed_type = 'windows'
817 else:
818 managed_type = 'posix'
819
820 control_state: dict[str, tuple[list[str], list[SshProcess]]] = {}
821 managed_state: dict[str, tuple[list[str], list[SshProcess]]] = {}
822
823 def pre_target(target: IntegrationTarget) -> None:
824 """Configure hosts for SSH port forwarding required by the specified target."""
825 forward_ssh_ports(args, control_connections, '%s_hosts_prepare.yml' % control_type, control_state, target, HostType.control, control_contexts)
826 forward_ssh_ports(args, managed_connections, '%s_hosts_prepare.yml' % managed_type, managed_state, target, HostType.managed, managed_contexts)
827
828 def post_target(target: IntegrationTarget) -> None:
829 """Clean up previously configured SSH port forwarding which was required by the specified target."""
830 cleanup_ssh_ports(args, control_connections, '%s_hosts_restore.yml' % control_type, control_state, target, HostType.control)
831 cleanup_ssh_ports(args, managed_connections, '%s_hosts_restore.yml' % managed_type, managed_state, target, HostType.managed)
832
833 else:
834 pre_target, post_target = None, None
835
836 return pre_target, post_target
837
838
839 def create_managed_contexts(control_contexts: dict[str, dict[str, ContainerAccess]]) -> dict[str, dict[str, ContainerAccess]]:
840 """Create managed contexts from the given control contexts."""
841 managed_contexts: dict[str, dict[str, ContainerAccess]] = {}
842
843 for context_name, control_context in control_contexts.items():
844 managed_context = managed_contexts[context_name] = {}
845
846 for container_name, control_container in control_context.items():
847 managed_context[container_name] = ContainerAccess(control_container.host_ip, control_container.names, None, dict(control_container.port_map()))
848
849 return managed_contexts
850
851
852 def forward_ssh_ports(
853 args: IntegrationConfig,
854 ssh_connections: t.Optional[list[SshConnectionDetail]],
855 playbook: str,
856 target_state: dict[str, tuple[list[str], list[SshProcess]]],
857 target: IntegrationTarget,
858 host_type: str,
859 contexts: dict[str, dict[str, ContainerAccess]],
860 ) -> None:
861 """Configure port forwarding using SSH and write hosts file entries."""
862 if ssh_connections is None:
863 return
864
865 test_context = None
866
867 for context_name, context in contexts.items():
868 context_alias = 'cloud/%s/' % context_name
869
870 if context_alias in target.aliases:
871 test_context = context
872 break
873
874 if not test_context:
875 return
876
877 if not ssh_connections:
878 if args.explain:
879 return
880
881 raise Exception('The %s host was not pre-configured for container access and SSH forwarding is not available.' % host_type)
882
883 redirects: list[tuple[int, str, int]] = []
884 messages = []
885
886 for container_name, container in test_context.items():
887 explain = []
888
889 for container_port, access_port in container.port_map():
890 if container.forwards:
891 redirects.append((container_port, container.host_ip, access_port))
892
893 explain.append('%d -> %s:%d' % (container_port, container.host_ip, access_port))
894 else:
895 explain.append('%s:%d' % (container.host_ip, container_port))
896
897 if explain:
898 if container.forwards:
899 message = 'Port forwards for the "%s" container have been established on the %s host' % (container_name, host_type)
900 else:
901 message = 'Ports for the "%s" container are available on the %s host as' % (container_name, host_type)
902
903 messages.append('%s:\n%s' % (message, '\n'.join(explain)))
904
905 hosts_entries = create_hosts_entries(test_context)
906 inventory = generate_ssh_inventory(ssh_connections)
907
908 with named_temporary_file(args, 'ssh-inventory-', '.json', None, inventory) as inventory_path: # type: str
909 run_playbook(args, inventory_path, playbook, capture=False, variables=dict(hosts_entries=hosts_entries))
910
911 ssh_processes: list[SshProcess] = []
912
913 if redirects:
914 for ssh in ssh_connections:
915 ssh_processes.append(create_ssh_port_redirects(args, ssh, redirects))
916
917 target_state[target.name] = (hosts_entries, ssh_processes)
918
919 for message in messages:
920 display.info(message, verbosity=1)
921
922
923 def cleanup_ssh_ports(
924 args: IntegrationConfig,
925 ssh_connections: list[SshConnectionDetail],
926 playbook: str,
927 target_state: dict[str, tuple[list[str], list[SshProcess]]],
928 target: IntegrationTarget,
929 host_type: str,
930 ) -> None:
931 """Stop previously configured SSH port forwarding and remove previously written hosts file entries."""
932 state = target_state.pop(target.name, None)
933
934 if not state:
935 return
936
937 (hosts_entries, ssh_processes) = state
938
939 inventory = generate_ssh_inventory(ssh_connections)
940
941 with named_temporary_file(args, 'ssh-inventory-', '.json', None, inventory) as inventory_path: # type: str
942 run_playbook(args, inventory_path, playbook, capture=False, variables=dict(hosts_entries=hosts_entries))
943
944 if ssh_processes:
945 for process in ssh_processes:
946 process.terminate()
947
948 display.info('Waiting for the %s host SSH port forwarding process(es) to terminate.' % host_type, verbosity=1)
949
950 for process in ssh_processes:
951 process.wait()