Debian Codegraph @

test/lib/ansible_test/_util/target/setup/requirements.py

raw
1 """A tool for installing test requirements on the controller and target host."""
2
3 from __future__ import annotations
4
5 # pylint: disable=wrong-import-position
6
7 import resource
8
9 # Setting a low soft RLIMIT_NOFILE value will improve the performance of subprocess.Popen on Python 2.x when close_fds=True.
10 # This will affect all Python subprocesses. It will also affect the current Python process if set before subprocess is imported for the first time.
11 SOFT_RLIMIT_NOFILE = 1024
12
13 CURRENT_RLIMIT_NOFILE = resource.getrlimit(resource.RLIMIT_NOFILE)
14 DESIRED_RLIMIT_NOFILE = (SOFT_RLIMIT_NOFILE, CURRENT_RLIMIT_NOFILE[1])
15
16 if DESIRED_RLIMIT_NOFILE < CURRENT_RLIMIT_NOFILE:
17 resource.setrlimit(resource.RLIMIT_NOFILE, DESIRED_RLIMIT_NOFILE)
18 CURRENT_RLIMIT_NOFILE = DESIRED_RLIMIT_NOFILE
19
20 import base64
21 import contextlib
22 import io
23 import json
24 import os
25 import shlex
26 import shutil
27 import subprocess
28 import sys
29 import tempfile
30 import typing as t
31 import urllib.request
32
33 ENCODING = 'utf-8'
34
35 Text = type(u'')
36
37 VERBOSITY = 0
38 CONSOLE = sys.stderr
39
40
41 def main(): # type: () -> None
42 """Main program entry point."""
43 global VERBOSITY # pylint: disable=global-statement
44
45 payload = json.loads(to_text(base64.b64decode(PAYLOAD)))
46
47 VERBOSITY = payload['verbosity']
48
49 script = payload['script']
50 commands = payload['commands']
51
52 with tempfile.NamedTemporaryFile(prefix='ansible-test-', suffix='-pip.py') as pip:
53 pip.write(to_bytes(script))
54 pip.flush()
55
56 for name, options in commands:
57 try:
58 globals()[name](pip.name, options)
59 except ApplicationError as ex:
60 print(ex)
61 sys.exit(1)
62
63
64 # noinspection PyUnusedLocal
65 def bootstrap(pip: str, options: dict[str, t.Any]) -> None:
66 """Bootstrap pip and related packages in an empty virtual environment."""
67 pip_version = options['pip_version']
68 packages = options['packages']
69 setuptools = options['setuptools']
70 wheel = options['wheel']
71
72 del options
73
74 url = 'https://ci-files.testing.ansible.com/ansible-test/get-pip-%s.py' % pip_version
75 cache_path = os.path.expanduser('~/.ansible/test/cache/get_pip_%s.py' % pip_version.replace(".", "_"))
76 temp_path = cache_path + '.download'
77
78 if os.path.exists(cache_path):
79 log('Using cached pip %s bootstrap script: %s' % (pip_version, cache_path))
80 else:
81 log('Downloading pip %s bootstrap script: %s' % (pip_version, url))
82
83 make_dirs(os.path.dirname(cache_path))
84
85 try:
86 download_file(url, temp_path)
87 except Exception as ex:
88 raise ApplicationError(("""
89 Download failed: %s
90
91 The bootstrap script can be manually downloaded and saved to: %s
92
93 If you're behind a proxy, consider commenting on the following GitHub issue:
94
95 https://github.com/ansible/ansible/issues/77304
96 """ % (ex, cache_path)).strip())
97
98 shutil.move(temp_path, cache_path)
99
100 log('Cached pip %s bootstrap script: %s' % (pip_version, cache_path))
101
102 env = common_pip_environment()
103 env.update(GET_PIP=cache_path)
104
105 pip_options = common_pip_options()
106 pip_options.extend(packages)
107
108 if not setuptools:
109 pip_options.append('--no-setuptools')
110
111 if not wheel:
112 pip_options.append('--no-wheel')
113
114 command = [sys.executable, pip] + pip_options
115
116 execute_command(command, env=env)
117
118
119 def install(pip: str, options: dict[str, t.Any]) -> None:
120 """Perform a pip install."""
121 requirements = options['requirements']
122 constraints = options['constraints']
123 packages = options['packages']
124
125 del options
126
127 tempdir = tempfile.mkdtemp(prefix='ansible-test-', suffix='-requirements')
128
129 try:
130 pip_options = common_pip_options()
131 pip_options.extend(packages)
132
133 for path, content in requirements:
134 if path.split(os.sep)[0] in ('test', 'requirements'):
135 # Support for pre-build is currently limited to requirements embedded in ansible-test and those used by ansible-core.
136 # Requirements from ansible-core can be found in the 'test' and 'requirements' directories.
137 # This feature will probably be extended to support collections after further testing.
138 # Requirements from collections can be found in the 'tests' directory.
139 for pre_build in parse_pre_build_instructions(content):
140 pre_build.execute(pip)
141
142 write_text_file(os.path.join(tempdir, path), content, True)
143 pip_options.extend(['-r', path])
144
145 for path, content in constraints:
146 write_text_file(os.path.join(tempdir, path), content, True)
147 pip_options.extend(['-c', path])
148
149 command = [sys.executable, pip, 'install'] + pip_options
150
151 env = common_pip_environment()
152
153 execute_command(command, env=env, cwd=tempdir)
154 finally:
155 remove_tree(tempdir)
156
157
158 class PreBuild:
159 """Parsed pre-build instructions."""
160
161 def __init__(self, requirement): # type: (str) -> None
162 self.requirement = requirement
163 self.constraints = [] # type: list[str]
164
165 def execute(self, pip): # type: (str) -> None
166 """Execute these pre-build instructions."""
167 tempdir = tempfile.mkdtemp(prefix='ansible-test-', suffix='-pre-build')
168
169 try:
170 pip_options = common_pip_options()
171 pip_options.append(self.requirement)
172
173 constraints = '\n'.join(self.constraints) + '\n'
174 constraints_path = os.path.join(tempdir, 'constraints.txt')
175
176 write_text_file(constraints_path, constraints, True)
177
178 env = common_pip_environment()
179 env.update(PIP_CONSTRAINT=constraints_path)
180
181 command = [sys.executable, pip, 'wheel'] + pip_options
182
183 execute_command(command, env=env, cwd=tempdir)
184 finally:
185 remove_tree(tempdir)
186
187
188 def parse_pre_build_instructions(requirements): # type: (str) -> list[PreBuild]
189 """Parse the given pip requirements and return a list of extracted pre-build instructions."""
190 # CAUTION: This code must be kept in sync with the sanity test hashing code in:
191 # test/lib/ansible_test/_internal/commands/sanity/__init__.py
192
193 pre_build_prefix = '# pre-build '
194 pre_build_requirement_prefix = pre_build_prefix + 'requirement: '
195 pre_build_constraint_prefix = pre_build_prefix + 'constraint: '
196
197 lines = requirements.splitlines()
198 pre_build_lines = [line for line in lines if line.startswith(pre_build_prefix)]
199
200 instructions = [] # type: list[PreBuild]
201
202 for line in pre_build_lines:
203 if line.startswith(pre_build_requirement_prefix):
204 instructions.append(PreBuild(line[len(pre_build_requirement_prefix):]))
205 elif line.startswith(pre_build_constraint_prefix):
206 instructions[-1].constraints.append(line[len(pre_build_constraint_prefix):])
207 else:
208 raise RuntimeError('Unsupported pre-build comment: ' + line)
209
210 return instructions
211
212
213 def uninstall(pip: str, options: dict[str, t.Any]) -> None:
214 """Perform a pip uninstall."""
215 packages = options['packages']
216 ignore_errors = options['ignore_errors']
217
218 del options
219
220 pip_options = common_pip_options()
221 pip_options.extend(packages)
222
223 command = [sys.executable, pip, 'uninstall', '-y'] + pip_options
224
225 env = common_pip_environment()
226
227 try:
228 execute_command(command, env=env, capture=True)
229 except SubprocessError:
230 if not ignore_errors:
231 raise
232
233
234 # noinspection PyUnusedLocal
235 def version(pip: str, options: dict[str, t.Any]) -> None:
236 """Report the pip version."""
237 del options
238
239 pip_options = common_pip_options()
240
241 command = [sys.executable, pip, '-V'] + pip_options
242
243 env = common_pip_environment()
244
245 execute_command(command, env=env, capture=True)
246
247
248 def common_pip_environment(): # type: () -> t.Dict[str, str]
249 """Return common environment variables used to run pip."""
250 env = os.environ.copy()
251
252 # When ansible-test installs requirements outside a virtual environment, it does so under one of two conditions:
253 # 1) The environment is an ephemeral one provisioned by ansible-test.
254 # 2) The user has provided the `--requirements` option to force installation of requirements.
255 # It seems reasonable to bypass PEP 668 checks in both of these cases.
256 # Doing so with an environment variable allows it to work under any version of pip which supports it, without breaking older versions.
257 # NOTE: pip version 23.0 enforces PEP 668 but does not support the override, in which case upgrading pip is required.
258 env.update(PIP_BREAK_SYSTEM_PACKAGES='1')
259
260 return env
261
262
263 def common_pip_options(): # type: () -> t.List[str]
264 """Return a list of common pip options."""
265 return [
266 '--disable-pip-version-check',
267 ]
268
269
270 def devnull(): # type: () -> t.IO[bytes]
271 """Return a file object that references devnull."""
272 try:
273 return devnull.file # type: ignore[attr-defined]
274 except AttributeError:
275 devnull.file = open(os.devnull, 'w+b') # type: ignore[attr-defined] # pylint: disable=consider-using-with
276
277 return devnull.file # type: ignore[attr-defined]
278
279
280 def download_file(url, path): # type: (str, str) -> None
281 """Download the given URL to the specified file path."""
282 with open(to_bytes(path), 'wb') as saved_file:
283 with contextlib.closing(urllib.request.urlopen(url)) as download:
284 shutil.copyfileobj(download, saved_file)
285
286
287 class ApplicationError(Exception):
288 """Base class for application exceptions."""
289
290
291 class SubprocessError(ApplicationError):
292 """A command returned a non-zero status."""
293
294 def __init__(self, cmd, status, stdout, stderr): # type: (t.List[str], int, str, str) -> None
295 message = 'A command failed with status %d: %s' % (status, shlex.join(cmd))
296
297 if stderr:
298 message += '\n>>> Standard Error\n%s' % stderr.strip()
299
300 if stdout:
301 message += '\n>>> Standard Output\n%s' % stdout.strip()
302
303 super(SubprocessError, self).__init__(message)
304
305
306 def log(message, verbosity=0): # type: (str, int) -> None
307 """Log a message to the console if the verbosity is high enough."""
308 if verbosity > VERBOSITY:
309 return
310
311 print(message, file=CONSOLE)
312 CONSOLE.flush()
313
314
315 def execute_command(cmd, cwd=None, capture=False, env=None): # type: (t.List[str], t.Optional[str], bool, t.Optional[t.Dict[str, str]]) -> None
316 """Execute the specified command."""
317 log('Execute command: %s' % shlex.join(cmd), verbosity=1)
318
319 cmd_bytes = [to_bytes(c) for c in cmd]
320
321 if capture:
322 stdout = subprocess.PIPE
323 stderr = subprocess.PIPE
324 else:
325 stdout = None
326 stderr = None
327
328 cwd_bytes = to_optional_bytes(cwd)
329 process = subprocess.Popen(cmd_bytes, cwd=cwd_bytes, stdin=devnull(), stdout=stdout, stderr=stderr, env=env) # pylint: disable=consider-using-with
330 stdout_bytes, stderr_bytes = process.communicate()
331 stdout_text = to_optional_text(stdout_bytes) or u''
332 stderr_text = to_optional_text(stderr_bytes) or u''
333
334 if process.returncode != 0:
335 raise SubprocessError(cmd, process.returncode, stdout_text, stderr_text)
336
337
338 def write_text_file(path, content, create_directories=False): # type: (str, str, bool) -> None
339 """Write the given text content to the specified path, optionally creating missing directories."""
340 if create_directories:
341 make_dirs(os.path.dirname(path))
342
343 with open_binary_file(path, 'wb') as file_obj:
344 file_obj.write(to_bytes(content))
345
346
347 def remove_tree(path): # type: (str) -> None
348 """Remove the specified directory tree."""
349 try:
350 shutil.rmtree(to_bytes(path))
351 except FileNotFoundError:
352 pass
353
354
355 def make_dirs(path): # type: (str) -> None
356 """Create a directory at path, including any necessary parent directories."""
357 os.makedirs(to_bytes(path), exist_ok=True)
358
359
360 def open_binary_file(path, mode='rb'): # type: (str, str) -> t.IO[bytes]
361 """Open the given path for binary access."""
362 if 'b' not in mode:
363 raise Exception('mode must include "b" for binary files: %s' % mode)
364
365 return io.open(to_bytes(path), mode) # pylint: disable=consider-using-with,unspecified-encoding
366
367
368 def to_optional_bytes(value, errors='strict'): # type: (t.Optional[str | bytes], str) -> t.Optional[bytes]
369 """Return the given value as bytes encoded using UTF-8 if not already bytes, or None if the value is None."""
370 return None if value is None else to_bytes(value, errors)
371
372
373 def to_optional_text(value, errors='strict'): # type: (t.Optional[str | bytes], str) -> t.Optional[t.Text]
374 """Return the given value as text decoded using UTF-8 if not already text, or None if the value is None."""
375 return None if value is None else to_text(value, errors)
376
377
378 def to_bytes(value, errors='strict'): # type: (str | bytes, str) -> bytes
379 """Return the given value as bytes encoded using UTF-8 if not already bytes."""
380 if isinstance(value, bytes):
381 return value
382
383 if isinstance(value, Text):
384 return value.encode(ENCODING, errors)
385
386 raise Exception('value is not bytes or text: %s' % type(value))
387
388
389 def to_text(value, errors='strict'): # type: (str | bytes, str) -> t.Text
390 """Return the given value as text decoded using UTF-8 if not already text."""
391 if isinstance(value, bytes):
392 return value.decode(ENCODING, errors)
393
394 if isinstance(value, Text):
395 return value
396
397 raise Exception('value is not bytes or text: %s' % type(value))
398
399
400 PAYLOAD = b'{payload}' # base-64 encoded JSON payload which will be populated before this script is executed
401
402 if __name__ == '__main__':
403 main()