Debian Codegraph @

test/lib/ansible_test/_internal/python_requirements.py

raw
1 """Python requirements management"""
2
3 from __future__ import annotations
4
5 import base64
6 import dataclasses
7 import json
8 import os
9 import typing as t
10
11 from .encoding import (
12 to_text,
13 to_bytes,
14 )
15
16 from .io import (
17 read_text_file,
18 )
19
20 from .util import (
21 ANSIBLE_TEST_DATA_ROOT,
22 ANSIBLE_TEST_TARGET_ROOT,
23 ApplicationError,
24 SubprocessError,
25 display,
26 )
27
28 from .util_common import (
29 check_pyyaml,
30 create_result_directories,
31 )
32
33 from .config import (
34 EnvironmentConfig,
35 IntegrationConfig,
36 UnitsConfig,
37 )
38
39 from .data import (
40 data_context,
41 )
42
43 from .host_configs import (
44 PosixConfig,
45 PythonConfig,
46 VirtualPythonConfig,
47 )
48
49 from .connections import (
50 LocalConnection,
51 Connection,
52 )
53
54 from .coverage_util import (
55 get_coverage_version,
56 )
57
58 if t.TYPE_CHECKING:
59 from .host_profiles import (
60 HostProfile,
61 )
62
63 QUIET_PIP_SCRIPT_PATH = os.path.join(ANSIBLE_TEST_TARGET_ROOT, 'setup', 'quiet_pip.py')
64 REQUIREMENTS_SCRIPT_PATH = os.path.join(ANSIBLE_TEST_TARGET_ROOT, 'setup', 'requirements.py')
65
66 # Pip Abstraction
67
68
69 class PipUnavailableError(ApplicationError):
70 """Exception raised when pip is not available."""
71
72 def __init__(self, python: PythonConfig) -> None:
73 super().__init__(f'Python {python.version} at "{python.path}" does not have pip available.')
74
75
76 @dataclasses.dataclass(frozen=True)
77 class PipCommand:
78 """Base class for pip commands."""
79
80 def serialize(self) -> tuple[str, dict[str, t.Any]]:
81 """Return a serialized representation of this command."""
82 name = type(self).__name__[3:].lower()
83 return name, self.__dict__
84
85
86 @dataclasses.dataclass(frozen=True)
87 class PipInstall(PipCommand):
88 """Details required to perform a pip install."""
89
90 requirements: list[tuple[str, str]]
91 constraints: list[tuple[str, str]]
92 packages: list[str]
93
94 def has_package(self, name: str) -> bool:
95 """Return True if the specified package will be installed, otherwise False."""
96 name = name.lower()
97
98 return (any(name in package.lower() for package in self.packages) or
99 any(name in contents.lower() for path, contents in self.requirements))
100
101
102 @dataclasses.dataclass(frozen=True)
103 class PipUninstall(PipCommand):
104 """Details required to perform a pip uninstall."""
105
106 packages: list[str]
107 ignore_errors: bool
108
109
110 @dataclasses.dataclass(frozen=True)
111 class PipVersion(PipCommand):
112 """Details required to get the pip version."""
113
114
115 @dataclasses.dataclass(frozen=True)
116 class PipBootstrap(PipCommand):
117 """Details required to bootstrap pip."""
118
119 pip_version: str
120 packages: list[str]
121 setuptools: bool
122 wheel: bool
123
124
125 # Entry Points
126
127
128 def install_requirements(
129 args: EnvironmentConfig,
130 host_profile: HostProfile | None,
131 python: PythonConfig,
132 ansible: bool = False,
133 command: bool = False,
134 coverage: bool = False,
135 controller: bool = True,
136 connection: t.Optional[Connection] = None,
137 ) -> None:
138 """Install requirements for the given Python using the specified arguments."""
139 create_result_directories(args)
140
141 if not requirements_allowed(args, controller):
142 post_install(host_profile)
143 return
144
145 if command and isinstance(args, (UnitsConfig, IntegrationConfig)) and args.coverage:
146 coverage = True
147
148 if ansible:
149 try:
150 ansible_cache = install_requirements.ansible_cache # type: ignore[attr-defined]
151 except AttributeError:
152 ansible_cache = install_requirements.ansible_cache = {} # type: ignore[attr-defined]
153
154 ansible_installed = ansible_cache.get(python.path)
155
156 if ansible_installed:
157 ansible = False
158 else:
159 ansible_cache[python.path] = True
160
161 commands = collect_requirements(
162 python=python,
163 controller=controller,
164 ansible=ansible,
165 command=args.command if command else None,
166 coverage=coverage,
167 minimize=False,
168 sanity=None,
169 )
170
171 from .host_profiles import DebuggableProfile
172
173 if isinstance(host_profile, DebuggableProfile) and host_profile.debugger and host_profile.debugger.get_python_package():
174 commands.append(PipInstall(
175 requirements=[],
176 constraints=[],
177 packages=[host_profile.debugger.get_python_package()],
178 ))
179
180 if not commands:
181 post_install(host_profile)
182 return
183
184 run_pip(args, python, commands, connection)
185
186 # false positive: pylint: disable=no-member
187 if any(isinstance(command, PipInstall) and command.has_package('pyyaml') for command in commands):
188 check_pyyaml(python)
189
190 post_install(host_profile)
191
192
193 def post_install(host_profile: HostProfile) -> None:
194 """Operations to perform after requirements are installed."""
195 from .host_profiles import DebuggableProfile
196
197 if isinstance(host_profile, DebuggableProfile):
198 host_profile.activate_debugger()
199
200
201 def collect_bootstrap(python: PythonConfig) -> list[PipCommand]:
202 """Return the details necessary to bootstrap pip into an empty virtual environment."""
203 infrastructure_packages = get_venv_packages(python)
204 pip_version = infrastructure_packages['pip']
205 packages = [f'{name}=={version}' for name, version in infrastructure_packages.items()]
206
207 bootstrap = PipBootstrap(
208 pip_version=pip_version,
209 packages=packages,
210 setuptools=False,
211 wheel=False,
212 )
213
214 return [bootstrap]
215
216
217 def collect_requirements(
218 python: PythonConfig,
219 controller: bool,
220 ansible: bool,
221 coverage: bool,
222 minimize: bool,
223 command: t.Optional[str],
224 sanity: t.Optional[str],
225 ) -> list[PipCommand]:
226 """Collect requirements for the given Python using the specified arguments."""
227 commands: list[PipCommand] = []
228
229 if coverage:
230 commands.extend(collect_package_install(packages=[f'coverage=={get_coverage_version(python.version).coverage_version}'], constraints=False))
231
232 if ansible or command:
233 commands.extend(collect_general_install(command, ansible))
234
235 if sanity:
236 commands.extend(collect_sanity_install(sanity))
237
238 if command == 'units':
239 commands.extend(collect_units_install())
240
241 if command in ('integration', 'windows-integration', 'network-integration'):
242 commands.extend(collect_integration_install(command, controller))
243
244 if (sanity or minimize) and any(isinstance(command, PipInstall) for command in commands):
245 # bootstrap the managed virtual environment, which will have been created without any installed packages
246 # sanity tests which install no packages skip this step
247 commands = collect_bootstrap(python) + commands
248
249 # most infrastructure packages can be removed from sanity test virtual environments after they've been created
250 # removing them reduces the size of environments cached in containers
251 uninstall_packages = list(get_venv_packages(python))
252
253 commands.extend(collect_uninstall(packages=uninstall_packages))
254
255 return commands
256
257
258 def run_pip(
259 args: EnvironmentConfig,
260 python: PythonConfig,
261 commands: list[PipCommand],
262 connection: t.Optional[Connection],
263 ) -> None:
264 """Run the specified pip commands for the given Python, and optionally the specified host."""
265 connection = connection or LocalConnection(args)
266 script = prepare_pip_script(commands)
267
268 if isinstance(args, IntegrationConfig):
269 # Integration tests can involve two hosts (controller and target).
270 # The connection type can be used to disambiguate between the two.
271 context = " (controller)" if isinstance(connection, LocalConnection) else " (target)"
272 else:
273 context = ""
274
275 if isinstance(python, VirtualPythonConfig):
276 context += " [venv]"
277
278 # The interpreter path is not included below.
279 # It can be seen by running ansible-test with increased verbosity (showing all commands executed).
280 display.info(f'Installing requirements for Python {python.version}{context}')
281
282 if not args.explain:
283 try:
284 connection.run([python.path], data=script, capture=False)
285 except SubprocessError:
286 script = prepare_pip_script([PipVersion()])
287
288 try:
289 connection.run([python.path], data=script, capture=True)
290 except SubprocessError as ex:
291 if 'pip is unavailable:' in ex.stdout + ex.stderr:
292 raise PipUnavailableError(python) from None
293
294 raise
295
296
297 # Collect
298
299
300 def collect_general_install(
301 command: t.Optional[str] = None,
302 ansible: bool = False,
303 ) -> list[PipInstall]:
304 """Return details necessary for the specified general-purpose pip install(s)."""
305 requirements_paths: list[tuple[str, str]] = []
306 constraints_paths: list[tuple[str, str]] = []
307
308 if ansible:
309 path = os.path.join(ANSIBLE_TEST_DATA_ROOT, 'requirements', 'ansible.txt')
310 requirements_paths.append((ANSIBLE_TEST_DATA_ROOT, path))
311
312 if command:
313 path = os.path.join(ANSIBLE_TEST_DATA_ROOT, 'requirements', f'{command}.txt')
314 requirements_paths.append((ANSIBLE_TEST_DATA_ROOT, path))
315
316 return collect_install(requirements_paths, constraints_paths)
317
318
319 def collect_package_install(packages: list[str], constraints: bool = True) -> list[PipInstall]:
320 """Return the details necessary to install the specified packages."""
321 return collect_install([], [], packages, constraints=constraints)
322
323
324 def collect_sanity_install(sanity: str) -> list[PipInstall]:
325 """Return the details necessary for the specified sanity pip install(s)."""
326 requirements_paths: list[tuple[str, str]] = []
327 constraints_paths: list[tuple[str, str]] = []
328
329 path = os.path.join(ANSIBLE_TEST_DATA_ROOT, 'requirements', f'sanity.{sanity}.txt')
330 requirements_paths.append((ANSIBLE_TEST_DATA_ROOT, path))
331
332 if data_context().content.is_ansible:
333 path = os.path.join(data_context().content.sanity_path, 'code-smell', f'{sanity}.requirements.txt')
334 requirements_paths.append((data_context().content.root, path))
335
336 return collect_install(requirements_paths, constraints_paths, constraints=False)
337
338
339 def collect_units_install() -> list[PipInstall]:
340 """Return details necessary for the specified units pip install(s)."""
341 requirements_paths: list[tuple[str, str]] = []
342 constraints_paths: list[tuple[str, str]] = []
343
344 path = os.path.join(data_context().content.unit_path, 'requirements.txt')
345 requirements_paths.append((data_context().content.root, path))
346
347 path = os.path.join(data_context().content.unit_path, 'constraints.txt')
348 constraints_paths.append((data_context().content.root, path))
349
350 return collect_install(requirements_paths, constraints_paths)
351
352
353 def collect_integration_install(command: str, controller: bool) -> list[PipInstall]:
354 """Return details necessary for the specified integration pip install(s)."""
355 requirements_paths: list[tuple[str, str]] = []
356 constraints_paths: list[tuple[str, str]] = []
357
358 # Support for prefixed files was added to ansible-test in ansible-core 2.12 when split controller/target testing was implemented.
359 # Previous versions of ansible-test only recognize non-prefixed files.
360 # If a prefixed file exists (even if empty), it takes precedence over the non-prefixed file.
361 prefixes = ('controller.' if controller else 'target.', '')
362
363 for prefix in prefixes:
364 path = os.path.join(data_context().content.integration_path, f'{prefix}requirements.txt')
365
366 if os.path.exists(path):
367 requirements_paths.append((data_context().content.root, path))
368 break
369
370 for prefix in prefixes:
371 path = os.path.join(data_context().content.integration_path, f'{command}.{prefix}requirements.txt')
372
373 if os.path.exists(path):
374 requirements_paths.append((data_context().content.root, path))
375 break
376
377 for prefix in prefixes:
378 path = os.path.join(data_context().content.integration_path, f'{prefix}constraints.txt')
379
380 if os.path.exists(path):
381 constraints_paths.append((data_context().content.root, path))
382 break
383
384 return collect_install(requirements_paths, constraints_paths)
385
386
387 def collect_install(
388 requirements_paths: list[tuple[str, str]],
389 constraints_paths: list[tuple[str, str]],
390 packages: t.Optional[list[str]] = None,
391 constraints: bool = True,
392 ) -> list[PipInstall]:
393 """Build a pip install list from the given requirements, constraints and packages."""
394 # listing content constraints first gives them priority over constraints provided by ansible-test
395 constraints_paths = list(constraints_paths)
396
397 if constraints:
398 constraints_paths.append((ANSIBLE_TEST_DATA_ROOT, os.path.join(ANSIBLE_TEST_DATA_ROOT, 'requirements', 'constraints.txt')))
399
400 requirements = [(os.path.relpath(path, root), read_text_file(path)) for root, path in requirements_paths if usable_pip_file(path)]
401 constraints = [(os.path.relpath(path, root), read_text_file(path)) for root, path in constraints_paths if usable_pip_file(path)]
402 packages = packages or []
403
404 if requirements or packages:
405 installs = [PipInstall(
406 requirements=requirements,
407 constraints=constraints,
408 packages=packages,
409 )]
410 else:
411 installs = []
412
413 return installs
414
415
416 def collect_uninstall(packages: list[str], ignore_errors: bool = False) -> list[PipUninstall]:
417 """Return the details necessary for the specified pip uninstall."""
418 uninstall = PipUninstall(
419 packages=packages,
420 ignore_errors=ignore_errors,
421 )
422
423 return [uninstall]
424
425
426 # Support
427
428
429 def get_venv_packages(python: PythonConfig) -> dict[str, str]:
430 """Return a dictionary of Python packages needed for a consistent virtual environment specific to the given Python version."""
431
432 # NOTE: This same information is needed for building the base-test-container image.
433 # See: https://github.com/ansible/base-test-container/blob/main/files/installer.py
434
435 default_packages = dict(
436 pip='25.2',
437 )
438
439 override_packages: dict[str, dict[str, str]] = {
440 }
441
442 packages = {name: version or default_packages[name] for name, version in override_packages.get(python.version, default_packages).items()}
443
444 return packages
445
446
447 def requirements_allowed(args: EnvironmentConfig, controller: bool) -> bool:
448 """
449 Return True if requirements can be installed, otherwise return False.
450
451 Requirements are only allowed if one of the following conditions is met:
452
453 The user specified --requirements manually.
454 The install will occur on the controller and the controller or controller Python is managed by ansible-test.
455 The install will occur on the target and the target or target Python is managed by ansible-test.
456 """
457 if args.requirements:
458 return True
459
460 if controller:
461 return args.controller.is_managed or args.controller.python.is_managed
462
463 target = args.only_targets(PosixConfig)[0]
464
465 return target.is_managed or target.python.is_managed
466
467
468 def prepare_pip_script(commands: list[PipCommand]) -> str:
469 """Generate a Python script to perform the requested pip commands."""
470 data = [command.serialize() for command in commands]
471
472 display.info(f'>>> Requirements Commands\n{json.dumps(data, indent=4)}', verbosity=3)
473
474 args = dict(
475 script=read_text_file(QUIET_PIP_SCRIPT_PATH),
476 verbosity=display.verbosity,
477 commands=data,
478 )
479
480 payload = to_text(base64.b64encode(to_bytes(json.dumps(args))))
481 path = REQUIREMENTS_SCRIPT_PATH
482 template = read_text_file(path)
483 script = template.format(payload=payload)
484
485 display.info(f'>>> Python Script from Template ({path})\n{script.strip()}', verbosity=4)
486
487 return script
488
489
490 def usable_pip_file(path: t.Optional[str]) -> bool:
491 """Return True if the specified pip file is usable, otherwise False."""
492 return bool(path) and os.path.exists(path) and bool(os.path.getsize(path))