Debian Codegraph @

lib/ansible/galaxy/dependency_resolution/providers.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright: (c) 2020-2021, Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 """Requirement provider interfaces."""
5
6 from __future__ import annotations
7
8 import collections.abc as _c
9 import functools
10 import typing as t
11
12 if t.TYPE_CHECKING:
13 from ansible.galaxy.collection.concrete_artifact_manager import (
14 ConcreteArtifactsManager,
15 )
16 from ansible.galaxy.collection.galaxy_api_proxy import MultiGalaxyAPIProxy
17 from ansible.galaxy.api import GalaxyAPI
18
19 from resolvelib.structs import RequirementInformation
20
21 from ansible.galaxy.collection.gpg import get_signature_from_source
22 from ansible.galaxy.dependency_resolution.dataclasses import (
23 Candidate,
24 Requirement,
25 AnsibleRequirement,
26 )
27 from ansible.galaxy.dependency_resolution.versioning import (
28 is_pre_release,
29 meets_requirements,
30 )
31 from ansible.utils.version import SemanticVersion, LooseVersion
32
33 try:
34 from resolvelib import AbstractProvider
35 from resolvelib import __version__ as resolvelib_version
36 except ImportError:
37 class AbstractProvider: # type: ignore[no-redef]
38 pass
39
40 resolvelib_version = '0.0.0'
41
42
43 # TODO: add python requirements to ansible-test's ansible-core distribution info and remove the hardcoded lowerbound/upperbound fallback
44 RESOLVELIB_LOWERBOUND = SemanticVersion("0.8.0")
45 RESOLVELIB_UPPERBOUND = SemanticVersion("2.0.0")
46 RESOLVELIB_VERSION = SemanticVersion.from_loose_version(LooseVersion(resolvelib_version))
47
48
49 class CollectionDependencyProvider(AbstractProvider):
50 """Delegate providing a requirement interface for the resolver."""
51
52 def __init__(
53 self,
54 apis: MultiGalaxyAPIProxy,
55 concrete_artifacts_manager: ConcreteArtifactsManager,
56 preferred_candidates: _c.Iterable[Candidate] | None = None,
57 with_deps: bool = True,
58 with_pre_releases: bool = False,
59 upgrade: bool = False,
60 include_signatures: bool = True,
61 ) -> None:
62 r"""Initialize helper attributes.
63
64 :param api: An instance of the multiple Galaxy APIs wrapper.
65
66 :param concrete_artifacts_manager: An instance of the caching \
67 concrete artifacts manager.
68
69 :param with_deps: A flag specifying whether the resolver \
70 should attempt to pull-in the deps of the \
71 requested requirements. On by default.
72
73 :param with_pre_releases: A flag specifying whether the \
74 resolver should skip pre-releases. \
75 Off by default.
76
77 :param upgrade: A flag specifying whether the resolver should \
78 skip matching versions that are not upgrades. \
79 Off by default.
80
81 :param include_signatures: A flag to determine whether to retrieve \
82 signatures from the Galaxy APIs and \
83 include signatures in matching Candidates. \
84 On by default.
85 """
86 self._api_proxy = apis
87 self._make_req_from_dict = functools.partial(
88 Requirement.from_requirement_dict,
89 art_mgr=concrete_artifacts_manager,
90 )
91 self._make_ansible_requirement = functools.partial(
92 AnsibleRequirement.from_collection,
93 concrete_artifacts_manager,
94 )
95 self._preferred_candidates = set(preferred_candidates or ())
96 self._with_deps = with_deps
97 self._with_pre_releases = with_pre_releases
98 self._upgrade = upgrade
99 self._include_signatures = include_signatures
100
101 def identify(
102 self,
103 requirement_or_candidate: Candidate | Requirement,
104 ) -> str:
105 """Given requirement or candidate, return an identifier for it.
106
107 This is used to identify a requirement or candidate, e.g.
108 whether two requirements should have their specifier parts
109 (version ranges or pins) merged, whether two candidates would
110 conflict with each other (because they have same name but
111 different versions).
112 """
113 return requirement_or_candidate.canonical_package_id
114
115 def get_preference(
116 self,
117 identifier: str,
118 resolutions: _c.Mapping[str, Candidate],
119 candidates: _c.Mapping[str, _c.Iterator[Candidate]],
120 information: _c.Mapping[
121 str,
122 _c.Iterator[RequirementInformation[Requirement, Candidate]],
123 ],
124 backtrack_causes: _c.Sequence[
125 RequirementInformation[Requirement, Candidate],
126 ],
127 ) -> float | int:
128 """Return sort key function return value for given requirement.
129
130 This result should be based on preference that is defined as
131 "I think this requirement should be resolved first".
132 The lower the return value is, the more preferred this
133 group of arguments is.
134
135 :param identifier: The value returned by ``identify()``.
136
137 :param resolutions: Mapping of identifier, candidate pairs.
138
139 :param candidates: Possible candidates for the identifier.
140 Mapping of identifier, list of candidate pairs.
141
142 :param information: Requirement information of each package.
143 Mapping of identifier, list of named tuple pairs.
144 The named tuples have the entries ``requirement`` and ``parent``.
145
146 :param backtrack_causes: Sequence of requirement information that were
147 the requirements that caused the resolver to most recently backtrack.
148
149 The preference could depend on various of issues, including
150 (not necessarily in this order):
151
152 * Is this package pinned in the current resolution result?
153
154 * How relaxed is the requirement? Stricter ones should
155 probably be worked on first? (I don't know, actually.)
156
157 * How many possibilities are there to satisfy this
158 requirement? Those with few left should likely be worked on
159 first, I guess?
160
161 * Are there any known conflicts for this requirement?
162 We should probably work on those with the most
163 known conflicts.
164
165 A sortable value should be returned (this will be used as the
166 `key` parameter of the built-in sorting function). The smaller
167 the value is, the more preferred this requirement is (i.e. the
168 sorting function is called with ``reverse=False``).
169 """
170 if any(
171 candidate in self._preferred_candidates
172 for candidate in candidates
173 ):
174 # NOTE: Prefer pre-installed candidates over newer versions
175 # NOTE: available from Galaxy or other sources.
176 return float('-inf')
177 return len(candidates)
178
179 def find_matches(
180 self,
181 identifier: str,
182 requirements: _c.Mapping[str, _c.Iterator[Requirement]],
183 incompatibilities: _c.Mapping[str, _c.Iterator[Candidate]],
184 ) -> list[Candidate]:
185 r"""Find all possible candidates satisfying given requirements.
186
187 This tries to get candidates based on the requirements' types.
188
189 For concrete requirements (SCM, dir, namespace dir, local or
190 remote archives), the one-and-only match is returned
191
192 For a "named" requirement, Galaxy-compatible APIs are consulted
193 to find concrete candidates for this requirement. If there's a
194 pre-installed candidate, it's prepended in front of others.
195 """
196 results = []
197 for match in self._find_matches(list(requirements[identifier])):
198 if any(match.ver == incompat.ver for incompat in incompatibilities[identifier]):
199 continue
200
201 match._requirements = list(requirements[identifier])
202 results.append(match)
203 return results
204
205 def _find_matches(self, requirements: list[Requirement]) -> list[Candidate]:
206 # FIXME: The first requirement may be a Git repo followed by
207 # FIXME: its cloned tmp dir. Using only the first one creates
208 # FIXME: loops that prevent any further dependency exploration.
209 # FIXME: We need to figure out how to prevent this.
210 first_req = requirements[0]
211 fqcn = first_req.fqcn
212 # The fqcn is guaranteed to be the same
213 version_req = "A SemVer-compliant version or '*' is required. See https://semver.org to learn how to compose it correctly. "
214 version_req += "This is an issue with the collection."
215
216 if first_req.type == "requires_ansible":
217 for r in requirements:
218 if r.has_candidate is None:
219 return []
220 return [first_req.has_candidate]
221
222 # If we're upgrading collections, we can't calculate preinstalled_candidates until the latest matches are found.
223 # Otherwise, we can potentially avoid a Galaxy API call by doing this first.
224 preinstalled_candidates = set()
225 if not self._upgrade and first_req.type == 'galaxy':
226 preinstalled_candidates = {
227 candidate for candidate in self._preferred_candidates
228 if candidate.fqcn == fqcn and
229 all(self.is_satisfied_by(requirement, candidate) for requirement in requirements)
230 }
231 try:
232 coll_versions: _c.Iterable[tuple[str, GalaxyAPI]] = (
233 [] if preinstalled_candidates
234 else self._api_proxy.get_collection_versions(first_req)
235 )
236 except TypeError as exc:
237 if first_req.is_concrete_artifact:
238 # Non hashable versions will cause a TypeError
239 raise ValueError(
240 f"Invalid version found for the collection '{first_req}'. {version_req}"
241 ) from exc
242 # Unexpected error from a Galaxy server
243 raise
244
245 if first_req.is_concrete_artifact:
246 # FIXME: do we assume that all the following artifacts are also concrete?
247 # FIXME: does using fqcn==None cause us problems here?
248
249 # Ensure the version found in the concrete artifact is SemVer-compliant
250 for version, req_src in coll_versions:
251 version_err = f"Invalid version found for the collection '{first_req}': {version} ({type(version)}). {version_req}"
252 # NOTE: The known cases causing the version to be a non-string object come from
253 # NOTE: the differences in how the YAML parser normalizes ambiguous values and
254 # NOTE: how the end-users sometimes expect them to be parsed. Unless the users
255 # NOTE: explicitly use the double quotes of one of the multiline string syntaxes
256 # NOTE: in the collection metadata file, PyYAML will parse a value containing
257 # NOTE: two dot-separated integers as `float`, a single integer as `int`, and 3+
258 # NOTE: integers as a `str`. In some cases, they may also use an empty value
259 # NOTE: which is normalized as `null` and turned into `None` in the Python-land.
260 # NOTE: Another known mistake is setting a minor part of the SemVer notation
261 # NOTE: skipping the "patch" bit like "1.0" which is assumed non-compliant even
262 # NOTE: after the conversion to string.
263 if not isinstance(version, str):
264 raise ValueError(version_err)
265 elif version != '*':
266 try:
267 SemanticVersion(version)
268 except ValueError as ex:
269 raise ValueError(version_err) from ex
270
271 return [
272 Candidate(fqcn, version, _none_src_server, first_req.type, None)
273 for version, _none_src_server in coll_versions
274 ]
275
276 latest_matches = []
277 signatures = []
278 extra_signature_sources: list[str] = []
279
280 discarding_pre_releases_acceptable = any(
281 not is_pre_release(candidate_version)
282 for candidate_version, _src_server in coll_versions
283 )
284
285 # NOTE: The optimization of conditionally looping over the requirements
286 # NOTE: is used to skip having to compute the pinned status of all
287 # NOTE: requirements and apply version normalization to the found ones.
288 all_pinned_requirement_version_numbers = {
289 # NOTE: Pinned versions can start with a number, but also with an
290 # NOTE: equals sign. Stripping it at the beginning should be
291 # NOTE: enough. If there's a space after equals, the second strip
292 # NOTE: will take care of it.
293 # NOTE: Without this conversion, requirements versions like
294 # NOTE: '1.2.3-alpha.4' work, but '=1.2.3-alpha.4' don't.
295 requirement.ver.lstrip('=').strip()
296 for requirement in requirements
297 if requirement.is_pinned
298 } if discarding_pre_releases_acceptable else set()
299
300 for version, src_server in coll_versions:
301 tmp_candidate = Candidate(fqcn, version, src_server, 'galaxy', None)
302
303 for requirement in requirements:
304 candidate_satisfies_requirement = self.is_satisfied_by(
305 requirement, tmp_candidate,
306 )
307 if not candidate_satisfies_requirement:
308 break
309
310 should_disregard_pre_release_candidate = (
311 # NOTE: Do not discard pre-release candidates in the
312 # NOTE: following cases:
313 # NOTE: * the end-user requested pre-releases explicitly;
314 # NOTE: * the candidate is a concrete artifact (e.g. a
315 # NOTE: Git repository, subdirs, a tarball URL, or a
316 # NOTE: local dir or file etc.);
317 # NOTE: * the candidate's pre-release version exactly
318 # NOTE: matches a version specifically requested by one
319 # NOTE: of the requirements in the current match
320 # NOTE: discovery round (i.e. matching a requirement
321 # NOTE: that is not a range but an explicit specific
322 # NOTE: version pin). This works when some requirements
323 # NOTE: request version ranges but others (possibly on
324 # NOTE: different dependency tree level depths) demand
325 # NOTE: pre-release dependency versions, even if those
326 # NOTE: dependencies are transitive.
327 is_pre_release(tmp_candidate.ver)
328 and discarding_pre_releases_acceptable
329 and not (
330 self._with_pre_releases
331 or tmp_candidate.is_concrete_artifact
332 or version in all_pinned_requirement_version_numbers
333 )
334 )
335 if should_disregard_pre_release_candidate:
336 break
337
338 # FIXME
339 # candidate_is_from_requested_source = (
340 # requirement.src is None # if this is true for some candidates but not all it will break key param - Nonetype can't be compared to str
341 # or requirement.src == candidate.src
342 # )
343 # if not candidate_is_from_requested_source:
344 # break
345
346 if not self._include_signatures:
347 continue
348
349 extra_signature_sources.extend(requirement.signature_sources or [])
350
351 else: # candidate satisfies requirements, `break` never happened
352 if self._include_signatures:
353 for extra_source in extra_signature_sources:
354 signatures.append(get_signature_from_source(extra_source))
355 latest_matches.append(
356 Candidate(fqcn, version, src_server, 'galaxy', frozenset(signatures))
357 )
358
359 latest_matches.sort(
360 key=lambda candidate: (
361 SemanticVersion(candidate.ver), candidate.src,
362 ),
363 reverse=True, # prefer newer versions over older ones
364 )
365
366 if not preinstalled_candidates:
367 preinstalled_candidates = {
368 candidate for candidate in self._preferred_candidates
369 if candidate.fqcn == fqcn and
370 (
371 # check if an upgrade is necessary
372 all(self.is_satisfied_by(requirement, candidate) for requirement in requirements) and
373 (
374 not self._upgrade or
375 # check if an upgrade is preferred
376 all(SemanticVersion(latest.ver) <= SemanticVersion(candidate.ver) for latest in latest_matches)
377 )
378 )
379 }
380
381 return list(preinstalled_candidates) + latest_matches
382
383 def is_satisfied_by(
384 self,
385 requirement: Requirement,
386 candidate: Candidate,
387 ) -> bool:
388 r"""Whether the given requirement is satisfiable by a candidate.
389
390 :param requirement: A requirement that produced the `candidate`.
391
392 :param candidate: A pinned candidate supposedly matching the \
393 `requirement` specifier. It is guaranteed to \
394 have been generated from the `requirement`.
395
396 :returns: Indication whether the `candidate` is a viable \
397 solution to the `requirement`.
398 """
399 # NOTE: This is a set of Pipenv-inspired optimizations. Ref:
400 # https://github.com/sarugaku/passa/blob/2ac00f1/src/passa/models/providers.py#L58-L74
401 if (
402 requirement.is_virtual or
403 candidate.is_virtual or
404 requirement.ver == '*'
405 ):
406 return True
407
408 if requirement.type == 'requires_ansible':
409 return requirement.is_satisfied_by(candidate)
410
411 return meets_requirements(
412 version=candidate.ver,
413 requirements=requirement.ver,
414 )
415
416 def get_dependencies(self, candidate: Candidate) -> t.Iterator[Requirement]:
417 r"""Get direct dependencies of a candidate.
418
419 :returns: A collection of requirements that `candidate` \
420 specifies as its dependencies.
421 """
422 if candidate.type == "requires_ansible":
423 return
424
425 # FIXME: If there's several galaxy servers set, there may be a
426 # FIXME: situation when the metadata of the same collection
427 # FIXME: differs. So how do we resolve this case? Priority?
428 # FIXME: Taking into account a pinned hash? Exploding on
429 # FIXME: any differences?
430 # NOTE: The underlying implementation currently uses first found
431 req_map = self._api_proxy.get_collection_dependencies(candidate)
432
433 if (requires_ansible := self._make_ansible_requirement(candidate)):
434 requires_ansible._parent = candidate
435 yield requires_ansible
436
437 # NOTE: This guard expression MUST perform an early exit only
438 # NOTE: after the `get_collection_dependencies()` call because
439 # NOTE: internally it populates the artifact URL of the candidate,
440 # NOTE: its SHA hash and the Galaxy API token. These are still
441 # NOTE: necessary with `--no-deps` because even with the disabled
442 # NOTE: dependency resolution the outer layer will still need to
443 # NOTE: know how to download and validate the artifact.
444 #
445 # NOTE: Virtual candidates should always return dependencies
446 # NOTE: because they are ephemeral and non-installable.
447 for dep_name, dep_req in req_map.items():
448 if not (self._with_deps or candidate.is_virtual):
449 continue
450 dependency = self._make_req_from_dict({'name': dep_name, 'version': dep_req})
451 dependency._parent = candidate
452 yield dependency