Debian Codegraph @

test/lib/ansible_test/_internal/pypi_proxy.py

raw
1 """PyPI proxy management."""
2
3 from __future__ import annotations
4
5 import os
6 import urllib.parse
7
8 from .io import (
9 write_text_file,
10 )
11
12 from .config import (
13 EnvironmentConfig,
14 )
15
16 from .host_configs import (
17 PosixConfig,
18 )
19
20 from .util import (
21 ApplicationError,
22 display,
23 )
24
25 from .util_common import (
26 ExitHandler,
27 process_scoped_temporary_file,
28 )
29
30 from .docker_util import (
31 docker_available,
32 )
33
34 from .containers import (
35 HostType,
36 get_container_database,
37 run_support_container,
38 )
39
40 from .ansible_util import (
41 run_playbook,
42 )
43
44 from .host_profiles import (
45 HostProfile,
46 )
47
48 from .inventory import (
49 create_posix_inventory,
50 )
51
52
53 def run_pypi_proxy(args: EnvironmentConfig, targets_use_pypi: bool) -> None:
54 """Run a PyPI proxy support container."""
55 if args.pypi_endpoint:
56 return # user has overridden the proxy endpoint, there is nothing to provision
57
58 versions_needing_proxy: tuple[str, ...] = tuple() # preserved for future use, no versions currently require this
59 posix_targets = [target for target in args.targets if isinstance(target, PosixConfig)]
60 need_proxy = targets_use_pypi and any(target.python.version in versions_needing_proxy for target in posix_targets)
61 use_proxy = args.pypi_proxy or need_proxy
62
63 if not use_proxy:
64 return
65
66 if not docker_available():
67 if args.pypi_proxy:
68 raise ApplicationError('Use of the PyPI proxy was requested, but Docker is not available.')
69
70 display.warning('Unable to use the PyPI proxy because Docker is not available. Installation of packages using `pip` may fail.')
71 return
72
73 image = 'quay.io/ansible/pypi-test-container:3.7.0'
74 port = 3141
75
76 run_support_container(
77 args=args,
78 context='__pypi_proxy__',
79 image=image,
80 name='pypi-test-container',
81 ports=[port],
82 )
83
84
85 def configure_pypi_proxy(args: EnvironmentConfig, profile: HostProfile) -> None:
86 """Configure the environment to use a PyPI proxy, if present."""
87 if args.pypi_endpoint:
88 pypi_endpoint = args.pypi_endpoint
89 else:
90 containers = get_container_database(args)
91 context = containers.data.get(HostType.control if profile.controller else HostType.managed, {}).get('__pypi_proxy__')
92
93 if not context:
94 return # proxy not configured
95
96 access = list(context.values())[0]
97
98 host = access.host_ip
99 port = dict(access.port_map())[3141]
100
101 pypi_endpoint = f'http://{host}:{port}/root/pypi/+simple/'
102
103 pypi_hostname = urllib.parse.urlparse(pypi_endpoint)[1].split(':')[0]
104
105 if profile.controller:
106 configure_controller_pypi_proxy(args, profile, pypi_endpoint, pypi_hostname)
107 else:
108 configure_target_pypi_proxy(args, profile, pypi_endpoint, pypi_hostname)
109
110
111 def configure_controller_pypi_proxy(args: EnvironmentConfig, profile: HostProfile, pypi_endpoint: str, pypi_hostname: str) -> None:
112 """Configure the controller environment to use a PyPI proxy."""
113 configure_pypi_proxy_pip(args, profile, pypi_endpoint, pypi_hostname)
114 configure_pypi_proxy_easy_install(args, profile, pypi_endpoint)
115
116
117 def configure_target_pypi_proxy(args: EnvironmentConfig, profile: HostProfile, pypi_endpoint: str, pypi_hostname: str) -> None:
118 """Configure the target environment to use a PyPI proxy."""
119 inventory_path = process_scoped_temporary_file(args)
120
121 create_posix_inventory(args, inventory_path, [profile])
122
123 def cleanup_pypi_proxy() -> None:
124 """Undo changes made to configure the PyPI proxy."""
125 run_playbook(args, inventory_path, 'pypi_proxy_restore.yml', capture=True)
126
127 force = 'yes' if profile.config.is_managed else 'no'
128
129 run_playbook(args, inventory_path, 'pypi_proxy_prepare.yml', capture=True, variables=dict(
130 pypi_endpoint=pypi_endpoint, pypi_hostname=pypi_hostname, force=force))
131
132 ExitHandler.register(cleanup_pypi_proxy)
133
134
135 def configure_pypi_proxy_pip(args: EnvironmentConfig, profile: HostProfile, pypi_endpoint: str, pypi_hostname: str) -> None:
136 """Configure a custom index for pip based installs."""
137 pip_conf_path = os.path.expanduser('~/.pip/pip.conf')
138 pip_conf = """
139 [global]
140 index-url = {0}
141 trusted-host = {1}
142 """.format(pypi_endpoint, pypi_hostname).strip()
143
144 def pip_conf_cleanup() -> None:
145 """Remove custom pip PyPI config."""
146 display.info('Removing custom PyPI config: %s' % pip_conf_path, verbosity=1)
147 os.remove(pip_conf_path)
148
149 if os.path.exists(pip_conf_path) and not profile.config.is_managed:
150 raise ApplicationError('Refusing to overwrite existing file: %s' % pip_conf_path)
151
152 display.info('Injecting custom PyPI config: %s' % pip_conf_path, verbosity=1)
153 display.info('Config: %s\n%s' % (pip_conf_path, pip_conf), verbosity=3)
154
155 if not args.explain:
156 write_text_file(pip_conf_path, pip_conf, True)
157 ExitHandler.register(pip_conf_cleanup)
158
159
160 def configure_pypi_proxy_easy_install(args: EnvironmentConfig, profile: HostProfile, pypi_endpoint: str) -> None:
161 """Configure a custom index for easy_install based installs."""
162 pydistutils_cfg_path = os.path.expanduser('~/.pydistutils.cfg')
163 pydistutils_cfg = """
164 [easy_install]
165 index_url = {0}
166 """.format(pypi_endpoint).strip()
167
168 if os.path.exists(pydistutils_cfg_path) and not profile.config.is_managed:
169 raise ApplicationError('Refusing to overwrite existing file: %s' % pydistutils_cfg_path)
170
171 def pydistutils_cfg_cleanup() -> None:
172 """Remove custom PyPI config."""
173 display.info('Removing custom PyPI config: %s' % pydistutils_cfg_path, verbosity=1)
174 os.remove(pydistutils_cfg_path)
175
176 display.info('Injecting custom PyPI config: %s' % pydistutils_cfg_path, verbosity=1)
177 display.info('Config: %s\n%s' % (pydistutils_cfg_path, pydistutils_cfg), verbosity=3)
178
179 if not args.explain:
180 write_text_file(pydistutils_cfg_path, pydistutils_cfg, True)
181 ExitHandler.register(pydistutils_cfg_cleanup)