Debian Codegraph @

test/lib/ansible_test/_internal/provisioning.py

raw
1 """Provision hosts for running tests."""
2
3 from __future__ import annotations
4
5 import collections.abc as c
6 import dataclasses
7 import functools
8 import itertools
9 import os
10 import pickle
11 import sys
12 import time
13 import traceback
14 import typing as t
15
16 from .config import (
17 EnvironmentConfig,
18 )
19
20 from .util import (
21 ApplicationError,
22 HostConnectionError,
23 display,
24 open_binary_file,
25 verify_sys_executable,
26 version_to_str,
27 type_guard,
28 )
29
30 from .util_common import (
31 ExitHandler,
32 )
33
34 from .thread import (
35 WrappedThread,
36 )
37
38 from .host_profiles import (
39 ControllerHostProfile,
40 DockerProfile,
41 HostProfile,
42 SshConnection,
43 SshTargetHostProfile,
44 create_host_profile,
45 )
46
47 from .pypi_proxy import (
48 run_pypi_proxy,
49 )
50
51
52 class PrimeContainers(ApplicationError):
53 """Exception raised to end execution early after priming containers."""
54
55
56 @dataclasses.dataclass(frozen=True)
57 class HostState:
58 """State of hosts and profiles to be passed to ansible-test during delegation."""
59
60 controller_profile: ControllerHostProfile
61 target_profiles: list[HostProfile]
62
63 @property
64 def profiles(self) -> list[HostProfile]:
65 """Return all the profiles as a list."""
66 return [t.cast(HostProfile, self.controller_profile)] + self.target_profiles
67
68 def serialize(self, path: str) -> None:
69 """Serialize the host state to the given path."""
70 with open_binary_file(path, 'wb') as state_file:
71 pickle.dump(self, state_file)
72
73 @staticmethod
74 def deserialize(args: EnvironmentConfig, path: str) -> HostState:
75 """Deserialize host state from the given args and path."""
76 with open_binary_file(path) as state_file:
77 host_state: HostState = pickle.load(state_file)
78
79 host_state.controller_profile.args = args
80
81 for target in host_state.target_profiles:
82 target.args = args
83
84 return host_state
85
86 def get_controller_target_connections(self) -> list[SshConnection]:
87 """Return SSH connection(s) for accessing all target hosts from the controller."""
88 return list(itertools.chain.from_iterable([target.get_controller_target_connections() for
89 target in self.target_profiles if isinstance(target, SshTargetHostProfile)]))
90
91 def targets[THostProfile: HostProfile](self, profile_type: t.Type[THostProfile]) -> list[THostProfile]:
92 """The list of target(s), verified to be of the specified type."""
93 if not self.target_profiles:
94 raise Exception('No target profiles found.')
95
96 assert type_guard(self.target_profiles, profile_type)
97
98 return t.cast(list[THostProfile], self.target_profiles)
99
100
101 def prepare_profiles[TEnvironmentConfig: EnvironmentConfig](
102 args: TEnvironmentConfig,
103 targets_use_pypi: bool = False,
104 skip_setup: bool = False,
105 requirements: t.Optional[c.Callable[[HostProfile], None]] = None,
106 ) -> HostState:
107 """
108 Create new profiles, or load existing ones, and return them.
109 If a requirements callback was provided, it will be used before configuring hosts if delegation has already been performed.
110 """
111 if args.host_path:
112 host_state = HostState.deserialize(args, os.path.join(args.host_path, 'state.dat'))
113 else:
114 run_pypi_proxy(args, targets_use_pypi)
115
116 controller_host_profile = t.cast(ControllerHostProfile, create_host_profile(args, args.controller, None))
117
118 host_state = HostState(
119 controller_profile=controller_host_profile,
120 target_profiles=[create_host_profile(args, target, controller_host_profile) for target in args.targets],
121 )
122
123 if args.prime_containers:
124 for host_profile in host_state.profiles:
125 if isinstance(host_profile, DockerProfile):
126 host_profile.provision()
127
128 raise PrimeContainers()
129
130 ExitHandler.register(functools.partial(cleanup_profiles, host_state))
131
132 for pre_profile in host_state.profiles:
133 pre_profile.pre_provision()
134
135 def provision(profile: HostProfile) -> None:
136 """Provision the given profile."""
137 profile.provision()
138
139 if not skip_setup:
140 profile.setup()
141
142 dispatch_jobs(
143 [(profile, WrappedThread(functools.partial(provision, profile), f'Provision: {profile}')) for profile in host_state.profiles]
144 )
145
146 host_state.controller_profile.configure()
147
148 if not args.delegate:
149 check_controller_python(args, host_state)
150 check_controller_powershell(args, host_state)
151
152 if requirements:
153 requirements(host_state.controller_profile)
154
155 def configure(profile: HostProfile) -> None:
156 """Configure the given profile."""
157 profile.wait()
158
159 if not skip_setup:
160 profile.configure()
161
162 if requirements:
163 requirements(profile)
164
165 dispatch_jobs(
166 [(profile, WrappedThread(functools.partial(configure, profile), f'Configure: {profile}')) for profile in host_state.target_profiles]
167 )
168
169 return host_state
170
171
172 def check_controller_python(args: EnvironmentConfig, host_state: HostState) -> None:
173 """Check the running environment to make sure it is what we expected."""
174 sys_version = version_to_str(sys.version_info[:2])
175 controller_python = host_state.controller_profile.python
176
177 if expected_executable := verify_sys_executable(controller_python.path):
178 raise ApplicationError(f'Running under Python interpreter "{sys.executable}" instead of "{expected_executable}".')
179
180 expected_version = controller_python.version
181
182 if expected_version != sys_version:
183 raise ApplicationError(f'Running under Python version {sys_version} instead of {expected_version}.')
184
185 args.controller_python = controller_python
186
187
188 def check_controller_powershell(args: EnvironmentConfig, host_state: HostState) -> None:
189 """Check the running environment to make sure it is what we expected."""
190 controller_powershell = host_state.controller_profile.powershell
191
192 args.controller_powershell = controller_powershell
193
194
195 def cleanup_profiles(host_state: HostState) -> None:
196 """Cleanup provisioned hosts when exiting."""
197 for profile in host_state.profiles:
198 profile.deprovision()
199
200
201 def dispatch_jobs(jobs: list[tuple[HostProfile, WrappedThread]]) -> None:
202 """Run the given profile job threads and wait for them to complete."""
203 for profile, thread in jobs:
204 thread.daemon = True
205 thread.start()
206
207 while any(thread.is_alive() for profile, thread in jobs):
208 time.sleep(1)
209
210 failed = False
211 connection_failures = 0
212
213 for profile, thread in jobs:
214 try:
215 thread.wait_for_result()
216 except HostConnectionError as ex:
217 display.error(f'Host {profile.config} connection failed:\n{ex}')
218 failed = True
219 connection_failures += 1
220 except ApplicationError as ex:
221 display.error(f'Host {profile.config} job failed:\n{ex}')
222 failed = True
223 except Exception as ex: # pylint: disable=broad-except
224 name = f'{"" if ex.__class__.__module__ == "builtins" else ex.__class__.__module__ + "."}{ex.__class__.__qualname__}'
225 display.error(f'Host {profile.config} job failed:\nTraceback (most recent call last):\n'
226 f'{"".join(traceback.format_tb(ex.__traceback__)).rstrip()}\n{name}: {ex}')
227 failed = True
228
229 if connection_failures:
230 raise HostConnectionError(f'Host job(s) failed, including {connection_failures} connection failure(s). See previous error(s) for details.')
231
232 if failed:
233 raise ApplicationError('Host job(s) failed. See previous error(s) for details.')