Debian Codegraph @

test/lib/ansible_test/_internal/completion.py

raw
1 """Loading, parsing and storing of completion configurations."""
2
3 from __future__ import annotations
4
5 import abc
6 import dataclasses
7 import enum
8 import os
9 import re
10 import sys
11 import typing as t
12
13 from .constants import (
14 CONTROLLER_PYTHON_VERSIONS,
15 SUPPORTED_PYTHON_VERSIONS,
16 )
17
18 from .util import (
19 ANSIBLE_TEST_DATA_ROOT,
20 cache,
21 read_lines_without_comments,
22 get_powershell_version_map,
23 str_to_version,
24 InternalError,
25 )
26
27 from .data import (
28 data_context,
29 )
30
31 from .become import (
32 SUPPORTED_BECOME_METHODS,
33 )
34
35
36 class CGroupVersion(enum.Enum):
37 """The control group version(s) required by a container."""
38
39 NONE = 'none'
40 V1_ONLY = 'v1-only'
41 V2_ONLY = 'v2-only'
42 V1_V2 = 'v1-v2'
43
44 def __repr__(self) -> str:
45 return f'{self.__class__.__name__}.{self.name}'
46
47
48 class AuditMode(enum.Enum):
49 """The audit requirements of a container."""
50
51 NONE = 'none'
52 REQUIRED = 'required'
53
54 def __repr__(self) -> str:
55 return f'{self.__class__.__name__}.{self.name}'
56
57
58 @dataclasses.dataclass(frozen=True)
59 class CompletionConfig(metaclass=abc.ABCMeta):
60 """Base class for completion configuration."""
61
62 name: str
63
64 @property
65 @abc.abstractmethod
66 def is_default(self) -> bool:
67 """True if the completion entry is only used for defaults, otherwise False."""
68
69 @property
70 def sort_key(self) -> tuple[str, tuple[int, ...]]:
71 """Key used for sorting completion entries."""
72 return '', (0,)
73
74
75 @dataclasses.dataclass(frozen=True)
76 class PosixCompletionConfig(CompletionConfig, metaclass=abc.ABCMeta):
77 """Base class for completion configuration of POSIX environments."""
78
79 @property
80 @abc.abstractmethod
81 def supported_pythons(self) -> list[str]:
82 """Return a list of the supported Python versions."""
83
84 @property
85 @abc.abstractmethod
86 def supported_powershells(self) -> list[str]:
87 """Return a list of the supported PowerShell versions."""
88
89 @abc.abstractmethod
90 def get_python_path(self, version: str) -> str:
91 """Return the path of the requested Python version."""
92
93 @abc.abstractmethod
94 def get_powershell_path(self, version: str | None) -> str | None:
95 """Return the path of the requested PowerShell version, or None if PowerShell is not available."""
96
97 def get_default_python(self, controller: bool) -> str:
98 """Return the default Python version for a controller or target as specified."""
99 context_pythons = CONTROLLER_PYTHON_VERSIONS if controller else SUPPORTED_PYTHON_VERSIONS
100 version = [python for python in self.supported_pythons if python in context_pythons][0]
101 return version
102
103 def get_default_powershell(self) -> str | None:
104 """Return the default PowerShell version, or None if there is no default."""
105 return None
106
107 @property
108 def controller_supported(self) -> bool:
109 """True if at least one Python version is provided which supports the controller, otherwise False."""
110 return any(version in CONTROLLER_PYTHON_VERSIONS for version in self.supported_pythons)
111
112
113 @dataclasses.dataclass(frozen=True)
114 class PythonCompletionConfig(PosixCompletionConfig, metaclass=abc.ABCMeta):
115 """Base class for completion configuration of Python environments."""
116
117 python: str = ''
118 python_dir: str = '/usr/bin'
119
120 @property
121 def supported_pythons(self) -> list[str]:
122 """Return a list of the supported Python versions."""
123 versions = self.python.split(',') if self.python else []
124 versions = [version for version in versions if version in SUPPORTED_PYTHON_VERSIONS]
125 return versions
126
127 def get_python_path(self, version: str) -> str:
128 """Return the path of the requested Python version."""
129 return os.path.join(self.python_dir, f'python{version}')
130
131
132 @dataclasses.dataclass(frozen=True)
133 class PowerShellCompletionConfig(PosixCompletionConfig, metaclass=abc.ABCMeta):
134 """Base class for completion configuration of PowerShell environments."""
135
136 powershell: str = ''
137 powershell_dir: str = '/usr/local/bin'
138
139 @property
140 def supported_powershells(self) -> list[str]:
141 """Return a list of the supported PowerShell versions."""
142 versions = self.powershell.split(',') if self.powershell else []
143 versions = [version for version in versions if version in get_powershell_version_map()]
144 return versions
145
146 def get_powershell_path(self, version: str | None) -> str | None:
147 """Return the path of the requested PowerShell version, or None if PowerShell is not available."""
148 if not version:
149 return None
150
151 return os.path.join(self.powershell_dir, f'pwsh{version}')
152
153
154 @dataclasses.dataclass(frozen=True)
155 class RemoteCompletionConfig(CompletionConfig):
156 """Base class for completion configuration of remote environments provisioned through Ansible Core CI."""
157
158 provider: t.Optional[str] = None
159 arch: t.Optional[str] = None
160
161 @property
162 def sort_key(self) -> tuple[str, tuple[int, ...]]:
163 """Key used for sorting completion entries."""
164 try:
165 version = str_to_version(self.version)
166 except ValueError:
167 version = (sys.maxsize,)
168
169 return self.platform, version
170
171 @property
172 def platform(self) -> str:
173 """The name of the platform."""
174 return self.name.partition('/')[0]
175
176 @property
177 def version(self) -> str:
178 """The version of the platform."""
179 return self.name.partition('/')[2]
180
181 @property
182 def is_default(self) -> bool:
183 """True if the completion entry is only used for defaults, otherwise False."""
184 return not self.version
185
186 def __post_init__(self):
187 if not self.provider:
188 raise Exception(f'Remote completion entry "{self.name}" must provide a "provider" setting.')
189
190 if not self.arch:
191 raise Exception(f'Remote completion entry "{self.name}" must provide a "arch" setting.')
192
193
194 @dataclasses.dataclass(frozen=True)
195 class InventoryCompletionConfig(CompletionConfig):
196 """Configuration for inventory files."""
197
198 def __init__(self) -> None:
199 super().__init__(name='inventory')
200
201 @property
202 def is_default(self) -> bool:
203 """True if the completion entry is only used for defaults, otherwise False."""
204 return False
205
206
207 @dataclasses.dataclass(frozen=True)
208 class PosixSshCompletionConfig(PythonCompletionConfig, PowerShellCompletionConfig):
209 """Configuration for a POSIX host reachable over SSH."""
210
211 def __init__(self, user: str, host: str) -> None:
212 super().__init__(
213 name=f'{user}@{host}',
214 python=','.join(SUPPORTED_PYTHON_VERSIONS),
215 )
216
217 @property
218 def is_default(self) -> bool:
219 """True if the completion entry is only used for defaults, otherwise False."""
220 return False
221
222
223 @dataclasses.dataclass(frozen=True)
224 class DockerCompletionConfig(PythonCompletionConfig, PowerShellCompletionConfig):
225 """Configuration for Docker containers."""
226
227 image: str = ''
228 seccomp: str = 'default'
229 cgroup: str = CGroupVersion.V1_V2.value
230 audit: str = AuditMode.REQUIRED.value # most containers need this, so the default is required, leaving it to be opt-out for containers which don't need it
231 placeholder: bool = False
232
233 @property
234 def sort_key(self) -> tuple[str, tuple[int, ...]]:
235 """Key used for sorting completion entries."""
236 match = re.match('^(?P<platform>[a-z]+)(?P<version>[0-9]*)$', self.name)
237 platform = match.group('platform')
238
239 try:
240 version = str_to_version(match.group('version'))
241 except ValueError:
242 version = (sys.maxsize,)
243
244 return platform, version
245
246 @property
247 def is_default(self) -> bool:
248 """True if the completion entry is only used for defaults, otherwise False."""
249 return False
250
251 @property
252 def audit_enum(self) -> AuditMode:
253 """The audit requirements for the container. Raises an exception if the value is invalid."""
254 try:
255 return AuditMode(self.audit)
256 except ValueError:
257 raise ValueError(f'Docker completion entry "{self.name}" has an invalid value "{self.audit}" for the "audit" setting.') from None
258
259 @property
260 def cgroup_enum(self) -> CGroupVersion:
261 """The control group version(s) required by the container. Raises an exception if the value is invalid."""
262 try:
263 return CGroupVersion(self.cgroup)
264 except ValueError:
265 raise ValueError(f'Docker completion entry "{self.name}" has an invalid value "{self.cgroup}" for the "cgroup" setting.') from None
266
267 def get_default_powershell(self) -> str | None:
268 """Return the default PowerShell version, or None if there is no default."""
269 return next(iter(self.supported_powershells), None)
270
271 def __post_init__(self):
272 if not self.image:
273 raise Exception(f'Docker completion entry "{self.name}" must provide an "image" setting.')
274
275 if not self.supported_pythons and not self.placeholder:
276 raise Exception(f'Docker completion entry "{self.name}" must provide a "python" setting.')
277
278 # verify properties can be correctly parsed to enums
279 assert self.audit_enum
280 assert self.cgroup_enum
281
282
283 @dataclasses.dataclass(frozen=True)
284 class NetworkRemoteCompletionConfig(RemoteCompletionConfig):
285 """Configuration for remote network platforms."""
286
287 collection: str = ''
288 connection: str = ''
289 placeholder: bool = False
290
291 def __post_init__(self):
292 if not self.placeholder:
293 super().__post_init__()
294
295
296 @dataclasses.dataclass(frozen=True)
297 class PosixRemoteCompletionConfig(RemoteCompletionConfig, PythonCompletionConfig, PowerShellCompletionConfig):
298 """Configuration for remote POSIX platforms."""
299
300 become: t.Optional[str] = None
301 placeholder: bool = False
302
303 def get_default_powershell(self) -> str | None:
304 """Return the default PowerShell version, or None if there is no default."""
305 return next(iter(self.supported_powershells), None)
306
307 def __post_init__(self):
308 if not self.placeholder:
309 super().__post_init__()
310
311 if self.become and self.become not in SUPPORTED_BECOME_METHODS:
312 raise Exception(f'POSIX remote completion entry "{self.name}" setting "become" must be omitted or one of: {", ".join(SUPPORTED_BECOME_METHODS)}')
313
314 if not self.supported_pythons:
315 if self.version and not self.placeholder:
316 raise Exception(f'POSIX remote completion entry "{self.name}" must provide a "python" setting.')
317 else:
318 if not self.version:
319 raise Exception(f'POSIX remote completion entry "{self.name}" is a platform default and cannot provide a "python" setting.')
320
321
322 @dataclasses.dataclass(frozen=True)
323 class WindowsRemoteCompletionConfig(RemoteCompletionConfig):
324 """Configuration for remote Windows platforms."""
325
326 connection: str = ''
327
328
329 def load_completion[TCompletionConfig: CompletionConfig](name: str, completion_type: t.Type[TCompletionConfig]) -> dict[str, TCompletionConfig]:
330 """Load the named completion entries, returning them in dictionary form using the specified completion type."""
331 lines = read_lines_without_comments(os.path.join(ANSIBLE_TEST_DATA_ROOT, 'completion', '%s.txt' % name), remove_blank_lines=True)
332
333 if data_context().content.collection:
334 context = 'collection'
335 else:
336 context = 'ansible-core'
337
338 items = {name: data for name, data in [parse_completion_entry(line) for line in lines] if data.get('context', context) == context}
339 aliases: dict[tuple[str, str], dict[str, str]] = {}
340 aliases_seen: set[str] = set()
341
342 for item_name, item in items.items():
343 item.pop('context', None)
344 item.pop('placeholder', None)
345
346 if alias := item.pop('alias', None):
347 for aliased_name in alias.split(','):
348 if aliased_name in aliases_seen:
349 raise InternalError(f"Duplicate alias {aliased_name!r} found for {name!r} completion.")
350
351 aliases_seen.add(aliased_name)
352 aliases[(aliased_name, item_name)] = item
353
354 completion = {name: completion_type(name=name, **data) for name, data in items.items()}
355 completion |= {an[0]: completion_type(name=an[1], **data) for an, data in aliases.items()}
356 completion = dict(sorted(completion.items(), key=lambda entry: entry[1].sort_key))
357
358 return completion
359
360
361 def parse_completion_entry(value: str) -> tuple[str, dict[str, str]]:
362 """Parse the given completion entry, returning the entry name and a dictionary of key/value settings."""
363 values = value.split()
364
365 name = values[0]
366 data = {kvp[0]: kvp[1] if len(kvp) > 1 else '' for kvp in [item.split('=', 1) for item in values[1:]]}
367
368 return name, data
369
370
371 def filter_completion[TCompletionConfig: CompletionConfig](
372 completion: dict[str, TCompletionConfig],
373 controller_only: bool = False,
374 include_defaults: bool = False,
375 ) -> dict[str, TCompletionConfig]:
376 """Return the given completion dictionary, filtering out configs which do not support the controller if controller_only is specified."""
377 if controller_only:
378 # The cast is needed because mypy gets confused here and forgets that completion values are TCompletionConfig.
379 completion = {name: t.cast(TCompletionConfig, config) for name, config in completion.items() if
380 isinstance(config, PosixCompletionConfig) and config.controller_supported}
381
382 if not include_defaults:
383 completion = {name: config for name, config in completion.items() if not config.is_default}
384
385 return completion
386
387
388 @cache
389 def docker_completion() -> dict[str, DockerCompletionConfig]:
390 """Return docker completion entries."""
391 return load_completion('docker', DockerCompletionConfig)
392
393
394 @cache
395 def remote_completion() -> dict[str, PosixRemoteCompletionConfig]:
396 """Return remote completion entries."""
397 return load_completion('remote', PosixRemoteCompletionConfig)
398
399
400 @cache
401 def windows_completion() -> dict[str, WindowsRemoteCompletionConfig]:
402 """Return windows completion entries."""
403 return load_completion('windows', WindowsRemoteCompletionConfig)
404
405
406 @cache
407 def network_completion() -> dict[str, NetworkRemoteCompletionConfig]:
408 """Return network completion entries."""
409 return load_completion('network', NetworkRemoteCompletionConfig)