Debian Codegraph @

lib/ansible/galaxy/collection/__init__.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright: (c) 2019-2021, Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 """Installed collections management package."""
5
6 from __future__ import annotations
7
8 import fnmatch
9 import functools
10 import glob
11 import inspect
12 import json
13 import os
14 import pathlib
15 import queue
16 import re
17 import shutil
18 import stat
19 import sys
20 import tarfile
21 import tempfile
22 import textwrap
23 import threading
24 import time
25 import typing as t
26
27 from collections import namedtuple
28 from contextlib import contextmanager
29 from dataclasses import dataclass
30 from hashlib import sha256
31 from io import BytesIO
32 from importlib.metadata import distribution
33 from importlib.resources import files
34 from itertools import chain
35 from operator import itemgetter
36
37 try:
38 from packaging.requirements import Requirement as PkgReq
39 except ImportError:
40 HAS_PACKAGING = False
41 else:
42 HAS_PACKAGING = True
43
44 try:
45 from distlib.manifest import Manifest
46 from distlib import DistlibException
47 except ImportError:
48 HAS_DISTLIB = False
49 else:
50 HAS_DISTLIB = True
51
52 if t.TYPE_CHECKING:
53 from ansible.galaxy.collection.concrete_artifact_manager import (
54 ConcreteArtifactsManager,
55 )
56
57 ManifestKeysType = t.Literal[
58 'collection_info', 'file_manifest_file', 'format',
59 ]
60 FileMetaKeysType = t.Literal[
61 'name',
62 'ftype',
63 'chksum_type',
64 'chksum_sha256',
65 'format',
66 ]
67 CollectionInfoKeysType = t.Literal[
68 # collection meta:
69 'namespace', 'name', 'version',
70 'authors', 'readme',
71 'tags', 'description',
72 'license', 'license_file',
73 'dependencies',
74 'repository', 'documentation',
75 'homepage', 'issues',
76
77 # files meta:
78 FileMetaKeysType,
79 ]
80 ManifestValueType = t.Dict[CollectionInfoKeysType, t.Union[int, str, t.List[str], t.Dict[str, str], None]]
81 CollectionManifestType = t.Dict[ManifestKeysType, ManifestValueType]
82 FileManifestEntryType = t.Dict[FileMetaKeysType, t.Union[str, int, None]]
83
84 class FilesManifestType(t.TypedDict):
85 files: t.List[FileManifestEntryType]
86 format: int
87
88 import ansible.constants as C
89 from ansible.errors import AnsibleError
90 from ansible.galaxy.api import GalaxyAPI
91 from ansible.galaxy.collection.concrete_artifact_manager import (
92 _consume_file,
93 _download_file,
94 _get_json_from_installed_dir,
95 _get_meta_from_src_dir,
96 _tarfile_extract,
97 )
98 from ansible.galaxy.collection.galaxy_api_proxy import MultiGalaxyAPIProxy
99 from ansible.galaxy.collection.gpg import (
100 run_gpg_verify,
101 parse_gpg_errors,
102 get_signature_from_source,
103 GPG_ERROR_MAP,
104 )
105 try:
106 from ansible.galaxy.dependency_resolution import (
107 build_collection_dependency_resolver,
108 )
109 from ansible.galaxy.dependency_resolution.errors import (
110 CollectionDependencyResolutionImpossible,
111 CollectionDependencyInconsistentCandidate,
112 )
113 from ansible.galaxy.dependency_resolution.providers import (
114 RESOLVELIB_VERSION,
115 RESOLVELIB_LOWERBOUND,
116 RESOLVELIB_UPPERBOUND,
117 )
118 except ImportError:
119 HAS_RESOLVELIB = False
120 else:
121 HAS_RESOLVELIB = True
122
123 from ansible.galaxy.dependency_resolution.dataclasses import (
124 Candidate, Requirement, _is_installed_collection_dir,
125 )
126 from ansible.galaxy.dependency_resolution.versioning import meets_requirements
127 from ansible.plugins.loader import get_all_plugin_loaders
128 from ansible.module_utils.common.file import S_IRWU_RG_RO, S_IRWXU_RXG_RXO, S_IXANY
129 from ansible.module_utils.common.sentinel import Sentinel
130 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
131 from ansible.module_utils.common.collections import is_sequence
132 from ansible.module_utils.common.yaml import yaml_dump
133 from ansible.utils.collection_loader import AnsibleCollectionRef
134 from ansible.utils.display import Display
135 from ansible.utils.hashing import secure_hash, secure_hash_s
136
137
138 display = Display()
139
140 MANIFEST_FORMAT = 1
141 MANIFEST_FILENAME = 'MANIFEST.json'
142
143 ModifiedContent = namedtuple('ModifiedContent', ['filename', 'expected', 'installed'])
144
145 SIGNATURE_COUNT_RE = r"^(?P<strict>\+)?(?:(?P<count>\d+)|(?P<all>all))$"
146
147
148 @dataclass
149 class ManifestControl:
150 directives: list[str] = None
151 omit_default_directives: bool = False
152
153 def __post_init__(self):
154 # Allow a dict representing this dataclass to be splatted directly.
155 # Requires attrs to have a default value, so anything with a default
156 # of None is swapped for its, potentially mutable, default
157 for field_name, field_type in inspect.get_annotations(type(self), eval_str=True).items():
158 if getattr(self, field_name) is None:
159 super().__setattr__(field_name, field_type())
160
161
162 class CollectionSignatureError(Exception):
163 def __init__(self, reasons=None, stdout=None, rc=None, ignore=False):
164 self.reasons = reasons
165 self.stdout = stdout
166 self.rc = rc
167 self.ignore = ignore
168
169 self._reason_wrapper = None
170
171 def _report_unexpected(self, collection_name):
172 return (
173 f"Unexpected error for '{collection_name}': "
174 f"GnuPG signature verification failed with the return code {self.rc} and output {self.stdout}"
175 )
176
177 def _report_expected(self, collection_name):
178 header = f"Signature verification failed for '{collection_name}' (return code {self.rc}):"
179 return header + self._format_reasons()
180
181 def _format_reasons(self):
182 if self._reason_wrapper is None:
183 self._reason_wrapper = textwrap.TextWrapper(
184 initial_indent=" * ", # 6 chars
185 subsequent_indent=" ", # 6 chars
186 )
187
188 wrapped_reasons = [
189 '\n'.join(self._reason_wrapper.wrap(reason))
190 for reason in self.reasons
191 ]
192
193 return '\n' + '\n'.join(wrapped_reasons)
194
195 def report(self, collection_name):
196 if self.reasons:
197 return self._report_expected(collection_name)
198
199 return self._report_unexpected(collection_name)
200
201
202 # FUTURE: expose actual verify result details for a collection on this object, maybe reimplement as dataclass on py3.8+
203 class CollectionVerifyResult:
204 def __init__(self, collection_name: str) -> None:
205 self.collection_name = collection_name
206 self.success = True
207
208
209 def verify_local_collection(local_collection, remote_collection, artifacts_manager):
210 # type: (Candidate, t.Optional[Candidate], ConcreteArtifactsManager) -> CollectionVerifyResult
211 """Verify integrity of the locally installed collection.
212
213 :param local_collection: Collection being checked.
214 :param remote_collection: Upstream collection (optional, if None, only verify local artifact)
215 :param artifacts_manager: Artifacts manager.
216 :return: a collection verify result object.
217 """
218 result = CollectionVerifyResult(local_collection.fqcn)
219
220 b_collection_path = to_bytes(local_collection.src, errors='surrogate_or_strict')
221
222 display.display("Verifying '{coll!s}'.".format(coll=local_collection))
223 display.display(
224 u"Installed collection found at '{path!s}'".
225 format(path=to_text(local_collection.src)),
226 )
227
228 modified_content = [] # type: list[ModifiedContent]
229
230 verify_local_only = remote_collection is None
231
232 # partial away the local FS detail so we can just ask generically during validation
233 get_json_from_validation_source = functools.partial(_get_json_from_installed_dir, b_collection_path)
234 get_hash_from_validation_source = functools.partial(_get_file_hash, b_collection_path)
235
236 if not verify_local_only:
237 # Compare installed version versus requirement version
238 if local_collection.ver != remote_collection.ver:
239 err = (
240 "{local_fqcn!s} has the version '{local_ver!s}' but "
241 "is being compared to '{remote_ver!s}'".format(
242 local_fqcn=local_collection.fqcn,
243 local_ver=local_collection.ver,
244 remote_ver=remote_collection.ver,
245 )
246 )
247 display.display(err)
248 result.success = False
249 return result
250
251 manifest_file = os.path.join(to_text(b_collection_path, errors='surrogate_or_strict'), MANIFEST_FILENAME)
252 signatures = list(local_collection.signatures)
253 if verify_local_only and local_collection.source_info is not None:
254 signatures = [info["signature"] for info in local_collection.source_info["signatures"]] + signatures
255 elif not verify_local_only and remote_collection.signatures:
256 signatures = list(remote_collection.signatures) + signatures
257
258 keyring_configured = artifacts_manager.keyring is not None
259 if not keyring_configured and signatures:
260 display.warning(
261 "The GnuPG keyring used for collection signature "
262 "verification was not configured but signatures were "
263 "provided by the Galaxy server. "
264 "Configure a keyring for ansible-galaxy to verify "
265 "the origin of the collection. "
266 "Skipping signature verification."
267 )
268 elif keyring_configured:
269 if not verify_file_signatures(
270 local_collection.fqcn,
271 manifest_file,
272 signatures,
273 artifacts_manager.keyring,
274 artifacts_manager.required_successful_signature_count,
275 artifacts_manager.ignore_signature_errors,
276 ):
277 result.success = False
278 return result
279 display.vvvv(f"GnuPG signature verification succeeded, verifying contents of {local_collection}")
280
281 if verify_local_only:
282 # since we're not downloading this, just seed it with the value from disk
283 manifest_hash = get_hash_from_validation_source(MANIFEST_FILENAME)
284 elif keyring_configured and remote_collection.signatures:
285 manifest_hash = get_hash_from_validation_source(MANIFEST_FILENAME)
286 else:
287 # fetch remote
288 # NOTE: AnsibleError is raised on URLError
289 b_temp_tar_path = artifacts_manager.get_artifact_path_from_unknown(remote_collection)
290
291 display.vvv(
292 u"Remote collection cached as '{path!s}'".format(path=to_text(b_temp_tar_path))
293 )
294
295 # partial away the tarball details so we can just ask generically during validation
296 get_json_from_validation_source = functools.partial(_get_json_from_tar_file, b_temp_tar_path)
297 get_hash_from_validation_source = functools.partial(_get_tar_file_hash, b_temp_tar_path)
298
299 # Verify the downloaded manifest hash matches the installed copy before verifying the file manifest
300 manifest_hash = get_hash_from_validation_source(MANIFEST_FILENAME)
301 _verify_file_hash(b_collection_path, MANIFEST_FILENAME, manifest_hash, modified_content)
302
303 display.display('MANIFEST.json hash: {manifest_hash}'.format(manifest_hash=manifest_hash))
304
305 manifest = get_json_from_validation_source(MANIFEST_FILENAME)
306
307 # Use the manifest to verify the file manifest checksum
308 file_manifest_data = manifest['file_manifest_file']
309 file_manifest_filename = file_manifest_data['name']
310 expected_hash = file_manifest_data['chksum_%s' % file_manifest_data['chksum_type']]
311
312 # Verify the file manifest before using it to verify individual files
313 _verify_file_hash(b_collection_path, file_manifest_filename, expected_hash, modified_content)
314 file_manifest = get_json_from_validation_source(file_manifest_filename)
315
316 collection_dirs = set()
317 collection_files = {
318 os.path.join(b_collection_path, b'MANIFEST.json'),
319 os.path.join(b_collection_path, b'FILES.json'),
320 }
321
322 # Use the file manifest to verify individual file checksums
323 for manifest_data in file_manifest['files']:
324 name = manifest_data['name']
325
326 if manifest_data['ftype'] == 'file':
327 collection_files.add(
328 os.path.join(b_collection_path, to_bytes(name, errors='surrogate_or_strict'))
329 )
330 expected_hash = manifest_data['chksum_%s' % manifest_data['chksum_type']]
331 _verify_file_hash(b_collection_path, name, expected_hash, modified_content)
332
333 if manifest_data['ftype'] == 'dir':
334 collection_dirs.add(
335 os.path.join(b_collection_path, to_bytes(name, errors='surrogate_or_strict'))
336 )
337
338 b_ignore_patterns = [
339 b'*.pyc',
340 ]
341
342 # Find any paths not in the FILES.json
343 for root, dirs, filenames in os.walk(b_collection_path):
344 for name in filenames:
345 full_path = os.path.join(root, name)
346 path = to_text(full_path[len(b_collection_path) + 1::], errors='surrogate_or_strict')
347 if any(fnmatch.fnmatch(full_path, b_pattern) for b_pattern in b_ignore_patterns):
348 display.v("Ignoring verification for %s" % to_text(full_path))
349 continue
350
351 if full_path not in collection_files:
352 modified_content.append(
353 ModifiedContent(filename=path, expected='the file does not exist', installed='the file exists')
354 )
355 for name in dirs:
356 full_path = os.path.join(root, name)
357 path = to_text(full_path[len(b_collection_path) + 1::], errors='surrogate_or_strict')
358
359 if full_path not in collection_dirs:
360 modified_content.append(
361 ModifiedContent(filename=path, expected='the directory does not exist', installed='the directory exists')
362 )
363
364 if modified_content:
365 result.success = False
366 display.display(
367 'Collection {fqcn!s} contains modified content '
368 'in the following files:'.
369 format(fqcn=to_text(local_collection.fqcn)),
370 )
371 for content_change in modified_content:
372 display.display(' %s' % content_change.filename)
373 display.v(" Expected: %s\n Found: %s" % (content_change.expected, content_change.installed))
374 else:
375 what = "are internally consistent with its manifest" if verify_local_only else "match the remote collection"
376 display.display(
377 "Successfully verified that checksums for '{coll!s}' {what!s}.".
378 format(coll=local_collection, what=what),
379 )
380
381 return result
382
383
384 def verify_file_signatures(fqcn, manifest_file, detached_signatures, keyring, required_successful_count, ignore_signature_errors):
385 # type: (str, str, list[str], str, str, list[str]) -> bool
386 successful = 0
387 error_messages = []
388
389 signature_count_requirements = re.match(SIGNATURE_COUNT_RE, required_successful_count).groupdict()
390
391 strict = signature_count_requirements['strict'] or False
392 require_all = signature_count_requirements['all']
393 require_count = signature_count_requirements['count']
394 if require_count is not None:
395 require_count = int(require_count)
396
397 for signature in detached_signatures:
398 signature = to_text(signature, errors='surrogate_or_strict')
399 try:
400 verify_file_signature(manifest_file, signature, keyring, ignore_signature_errors)
401 except CollectionSignatureError as error:
402 if error.ignore:
403 # Do not include ignored errors in either the failed or successful count
404 continue
405 error_messages.append(error.report(fqcn))
406 else:
407 successful += 1
408
409 if require_all:
410 continue
411
412 if successful == require_count:
413 break
414
415 if strict and not successful:
416 verified = False
417 display.display(f"Signature verification failed for '{fqcn}': no successful signatures")
418 elif require_all:
419 verified = not error_messages
420 if not verified:
421 display.display(f"Signature verification failed for '{fqcn}': some signatures failed")
422 else:
423 verified = not detached_signatures or require_count == successful
424 if not verified:
425 display.display(f"Signature verification failed for '{fqcn}': fewer successful signatures than required")
426
427 if not verified:
428 for msg in error_messages:
429 display.vvvv(msg)
430
431 return verified
432
433
434 def verify_file_signature(manifest_file, detached_signature, keyring, ignore_signature_errors):
435 # type: (str, str, str, list[str]) -> None
436 """Run the gpg command and parse any errors. Raises CollectionSignatureError on failure."""
437 gpg_result, gpg_verification_rc = run_gpg_verify(manifest_file, detached_signature, keyring, display)
438
439 if gpg_result:
440 errors = parse_gpg_errors(gpg_result)
441 try:
442 error = next(errors)
443 except StopIteration:
444 pass
445 else:
446 reasons = []
447 ignored_reasons = 0
448
449 for error in chain([error], errors):
450 # Get error status (dict key) from the class (dict value)
451 status_code = list(GPG_ERROR_MAP.keys())[list(GPG_ERROR_MAP.values()).index(error.__class__)]
452 if status_code in ignore_signature_errors:
453 ignored_reasons += 1
454 reasons.append(error.get_gpg_error_description())
455
456 ignore = len(reasons) == ignored_reasons
457 raise CollectionSignatureError(reasons=set(reasons), stdout=gpg_result, rc=gpg_verification_rc, ignore=ignore)
458
459 if gpg_verification_rc:
460 raise CollectionSignatureError(stdout=gpg_result, rc=gpg_verification_rc)
461
462 # No errors and rc is 0, verify was successful
463 return None
464
465
466 def build_collection(u_collection_path, u_output_path, force):
467 # type: (str, str, bool) -> str
468 """Creates the Ansible collection artifact in a .tar.gz file.
469
470 :param u_collection_path: The path to the collection to build. This should be the directory that contains the
471 galaxy.yml file.
472 :param u_output_path: The path to create the collection build artifact. This should be a directory.
473 :param force: Whether to overwrite an existing collection build artifact or fail.
474 :return: The path to the collection build artifact.
475 """
476 b_collection_path = to_bytes(u_collection_path, errors='surrogate_or_strict')
477 try:
478 collection_meta = _get_meta_from_src_dir(b_collection_path)
479 except LookupError as lookup_err:
480 raise AnsibleError(to_native(lookup_err)) from lookup_err
481
482 collection_manifest = _build_manifest(**collection_meta)
483 file_manifest = _build_files_manifest(
484 b_collection_path,
485 collection_meta['namespace'], # type: ignore[arg-type]
486 collection_meta['name'], # type: ignore[arg-type]
487 collection_meta['build_ignore'], # type: ignore[arg-type]
488 collection_meta['manifest'], # type: ignore[arg-type]
489 collection_meta['license_file'], # type: ignore[arg-type]
490 )
491
492 artifact_tarball_file_name = '{ns!s}-{name!s}-{ver!s}.tar.gz'.format(
493 name=collection_meta['name'],
494 ns=collection_meta['namespace'],
495 ver=collection_meta['version'],
496 )
497 b_collection_output = os.path.join(
498 to_bytes(u_output_path),
499 to_bytes(artifact_tarball_file_name, errors='surrogate_or_strict'),
500 )
501
502 if os.path.exists(b_collection_output):
503 if os.path.isdir(b_collection_output):
504 raise AnsibleError("The output collection artifact '%s' already exists, "
505 "but is a directory - aborting" % to_native(b_collection_output))
506 elif not force:
507 raise AnsibleError("The file '%s' already exists. You can use --force to re-create "
508 "the collection artifact." % to_native(b_collection_output))
509
510 collection_output = _build_collection_tar(b_collection_path, b_collection_output, collection_manifest, file_manifest)
511 return collection_output
512
513
514 def download_collections(
515 collections, # type: t.Iterable[Requirement]
516 output_path, # type: str
517 apis, # type: t.Iterable[GalaxyAPI]
518 no_deps, # type: bool
519 allow_pre_release, # type: bool
520 artifacts_manager, # type: ConcreteArtifactsManager
521 ): # type: (...) -> None
522 """Download Ansible collections as their tarball from a Galaxy server to the path specified and creates a requirements
523 file of the downloaded requirements to be used for an install.
524
525 :param collections: The collections to download, should be a list of tuples with (name, requirement, Galaxy Server).
526 :param output_path: The path to download the collections to.
527 :param apis: A list of GalaxyAPIs to query when search for a collection.
528 :param validate_certs: Whether to validate the certificate if downloading a tarball from a non-Galaxy host.
529 :param no_deps: Ignore any collection dependencies and only download the base requirements.
530 :param allow_pre_release: Do not ignore pre-release versions when selecting the latest.
531 """
532 with _display_progress("Process download dependency map"):
533 dep_map = _resolve_depenency_map(
534 set(collections),
535 galaxy_apis=apis,
536 preferred_candidates=None,
537 concrete_artifacts_manager=artifacts_manager,
538 no_deps=no_deps,
539 allow_pre_release=allow_pre_release,
540 upgrade=False,
541 # Avoid overhead getting signatures since they are not currently applicable to downloaded collections
542 include_signatures=False,
543 offline=False,
544 )
545
546 b_output_path = to_bytes(output_path, errors='surrogate_or_strict')
547
548 requirements = []
549 with _display_progress(
550 "Starting collection download process to '{path!s}'".
551 format(path=output_path),
552 ):
553 for fqcn, concrete_coll_pin in dep_map.copy().items(): # FIXME: move into the provider
554 if concrete_coll_pin.type == "requires_ansible":
555 continue
556 if concrete_coll_pin.is_virtual:
557 display.display(
558 '{coll!s} is not downloadable'.
559 format(coll=to_text(concrete_coll_pin)),
560 )
561 continue
562
563 display.display(
564 u"Downloading collection '{coll!s}' to '{path!s}'".
565 format(coll=to_text(concrete_coll_pin), path=to_text(b_output_path)),
566 )
567
568 b_src_path = artifacts_manager.get_artifact_path_from_unknown(concrete_coll_pin)
569
570 b_dest_path = os.path.join(
571 b_output_path,
572 os.path.basename(b_src_path),
573 )
574
575 if concrete_coll_pin.is_dir:
576 b_dest_path = to_bytes(
577 build_collection(
578 to_text(b_src_path, errors='surrogate_or_strict'),
579 to_text(output_path, errors='surrogate_or_strict'),
580 force=True,
581 ),
582 errors='surrogate_or_strict',
583 )
584 else:
585 shutil.copy(to_native(b_src_path), to_native(b_dest_path))
586
587 display.display(
588 "Collection '{coll!s}' was downloaded successfully".
589 format(coll=concrete_coll_pin),
590 )
591 requirements.append({
592 # FIXME: Consider using a more specific upgraded format
593 # FIXME: having FQCN in the name field, with src field
594 # FIXME: pointing to the file path, and explicitly set
595 # FIXME: type. If version and name are set, it'd
596 # FIXME: perform validation against the actual metadata
597 # FIXME: in the artifact src points at.
598 'name': to_native(os.path.basename(b_dest_path)),
599 'version': concrete_coll_pin.ver,
600 })
601
602 requirements_path = os.path.join(output_path, 'requirements.yml')
603 b_requirements_path = to_bytes(
604 requirements_path, errors='surrogate_or_strict',
605 )
606 display.display(
607 u'Writing requirements.yml file of downloaded collections '
608 "to '{path!s}'".format(path=to_text(requirements_path)),
609 )
610 yaml_bytes = to_bytes(
611 yaml_dump({'collections': requirements}),
612 errors='surrogate_or_strict',
613 )
614 with open(b_requirements_path, mode='wb') as req_fd:
615 req_fd.write(yaml_bytes)
616
617
618 def publish_collection(collection_path, api, wait, timeout):
619 """Publish an Ansible collection tarball into an Ansible Galaxy server.
620
621 :param collection_path: The path to the collection tarball to publish.
622 :param api: A GalaxyAPI to publish the collection to.
623 :param wait: Whether to wait until the import process is complete.
624 :param timeout: The time in seconds to wait for the import process to finish, 0 is indefinite.
625 """
626 import_uri = api.publish_collection(collection_path)
627
628 if wait:
629 with _display_progress(
630 "Collection has been published to the Galaxy server "
631 "{api.name!s} {api.api_server!s}".format(api=api),
632 ):
633 api.wait_import_task(import_uri, timeout)
634 display.display("Collection has been successfully published and imported to the Galaxy server %s %s"
635 % (api.name, api.api_server))
636 else:
637 display.display("Collection has been pushed to the Galaxy server %s %s, not waiting until import has "
638 "completed due to --no-wait being set. Import task results can be found at %s"
639 % (api.name, api.api_server, import_uri))
640
641
642 def install_collections(
643 collections, # type: t.Iterable[Requirement]
644 output_path, # type: str
645 apis, # type: t.Iterable[GalaxyAPI]
646 ignore_errors, # type: bool
647 no_deps, # type: bool
648 force, # type: bool
649 force_deps, # type: bool
650 upgrade, # type: bool
651 allow_pre_release, # type: bool
652 artifacts_manager, # type: ConcreteArtifactsManager
653 disable_gpg_verify, # type: bool
654 offline, # type: bool
655 read_requirement_paths, # type: set[str]
656 ): # type: (...) -> None
657 """Install Ansible collections to the path specified.
658
659 :param collections: The collections to install.
660 :param output_path: The path to install the collections to.
661 :param apis: A list of GalaxyAPIs to query when searching for a collection.
662 :param validate_certs: Whether to validate the certificates if downloading a tarball.
663 :param ignore_errors: Whether to ignore any errors when installing the collection.
664 :param no_deps: Ignore any collection dependencies and only install the base requirements.
665 :param force: Re-install a collection if it has already been installed.
666 :param force_deps: Re-install a collection as well as its dependencies if they have already been installed.
667 """
668 existing_collections = {
669 Requirement(coll.fqcn, coll.ver, coll.src, coll.type, None)
670 for path in {output_path} | read_requirement_paths
671 for coll in find_existing_collections(path, artifacts_manager)
672 }
673
674 unsatisfied_requirements = set(
675 chain.from_iterable(
676 (
677 Requirement.from_dir_path(to_bytes(sub_coll), artifacts_manager)
678 for sub_coll in (
679 artifacts_manager.
680 get_direct_collection_dependencies(install_req).
681 keys()
682 )
683 )
684 if install_req.is_subdirs else (install_req, )
685 for install_req in collections
686 ),
687 )
688 requested_requirements_names = {req.fqcn for req in unsatisfied_requirements}
689
690 # NOTE: Don't attempt to reevaluate already installed deps
691 # NOTE: unless `--force` or `--force-with-deps` is passed
692 unsatisfied_requirements -= set() if force or force_deps else {
693 req
694 for req in unsatisfied_requirements
695 for exs in existing_collections
696 if req.fqcn == exs.fqcn and meets_requirements(exs.ver, req.ver)
697 }
698
699 if not unsatisfied_requirements and not upgrade:
700 display.display(
701 'Nothing to do. All requested collections are already '
702 'installed. If you want to reinstall them, '
703 'consider using `--force`.'
704 )
705 return
706
707 # FIXME: This probably needs to be improved to
708 # FIXME: properly match differing src/type.
709 existing_non_requested_collections = {
710 coll for coll in existing_collections
711 if coll.fqcn not in requested_requirements_names
712 }
713
714 preferred_requirements = (
715 [] if force_deps
716 else existing_non_requested_collections if force
717 else existing_collections
718 )
719 preferred_collections = {
720 # NOTE: No need to include signatures if the collection is already installed
721 Candidate(coll.fqcn, coll.ver, coll.src, coll.type, None)
722 for coll in preferred_requirements
723 }
724 with _display_progress("Process install dependency map"):
725 dependency_map = _resolve_depenency_map(
726 collections,
727 galaxy_apis=apis,
728 preferred_candidates=preferred_collections,
729 concrete_artifacts_manager=artifacts_manager,
730 no_deps=no_deps,
731 allow_pre_release=allow_pre_release,
732 upgrade=upgrade,
733 include_signatures=not disable_gpg_verify,
734 offline=offline,
735 )
736
737 keyring_exists = artifacts_manager.keyring is not None
738 with _display_progress("Starting collection install process"):
739 for fqcn, concrete_coll_pin in dependency_map.items():
740 if concrete_coll_pin.type == "requires_ansible":
741 continue
742 if concrete_coll_pin.is_virtual:
743 display.vvvv(
744 "Encountered {coll!s}, skipping.".
745 format(coll=to_text(concrete_coll_pin)),
746 )
747 continue
748
749 if concrete_coll_pin in preferred_collections:
750 display.display(
751 "'{coll!s}' is already installed, skipping.".
752 format(coll=to_text(concrete_coll_pin)),
753 )
754 continue
755
756 if not disable_gpg_verify and concrete_coll_pin.signatures and not keyring_exists:
757 # Duplicate warning msgs are not displayed
758 display.warning(
759 "The GnuPG keyring used for collection signature "
760 "verification was not configured but signatures were "
761 "provided by the Galaxy server to verify authenticity. "
762 "Configure a keyring for ansible-galaxy to use "
763 "or disable signature verification. "
764 "Skipping signature verification."
765 )
766
767 if concrete_coll_pin.type == 'galaxy':
768 concrete_coll_pin = concrete_coll_pin.with_signatures_repopulated()
769
770 try:
771 install(concrete_coll_pin, output_path, artifacts_manager)
772 except AnsibleError as err:
773 if ignore_errors:
774 display.warning(
775 'Failed to install collection {coll!s} but skipping '
776 'due to --ignore-errors being set. Error: {error!s}'.
777 format(
778 coll=to_text(concrete_coll_pin),
779 error=to_text(err),
780 )
781 )
782 else:
783 raise
784
785
786 # NOTE: imported in ansible.cli.galaxy
787 def validate_collection_name(name): # type: (str) -> str
788 """Validates the collection name as an input from the user or a requirements file fit the requirements.
789
790 :param name: The input name with optional range specifier split by ':'.
791 :return: The input value, required for argparse validation.
792 """
793 collection, dummy, dummy = name.partition(':')
794 if AnsibleCollectionRef.is_valid_collection_name(collection):
795 return name
796
797 raise AnsibleError("Invalid collection name '%s', "
798 "name must be in the format <namespace>.<collection>. \n"
799 "Please make sure namespace and collection name contains "
800 "characters from [a-zA-Z0-9_] only." % name)
801
802
803 # NOTE: imported in ansible.cli.galaxy
804 def validate_collection_path(collection_path): # type: (str) -> str
805 """Ensure a given path ends with 'ansible_collections'
806
807 :param collection_path: The path that should end in 'ansible_collections'
808 :return: collection_path ending in 'ansible_collections' if it does not already.
809 """
810
811 if os.path.split(collection_path)[1] != 'ansible_collections':
812 return os.path.join(collection_path, 'ansible_collections')
813
814 return collection_path
815
816
817 def verify_collections(
818 collections, # type: t.Iterable[Requirement]
819 search_paths, # type: t.Iterable[str]
820 apis, # type: t.Iterable[GalaxyAPI]
821 ignore_errors, # type: bool
822 local_verify_only, # type: bool
823 artifacts_manager, # type: ConcreteArtifactsManager
824 ): # type: (...) -> list[CollectionVerifyResult]
825 r"""Verify the integrity of locally installed collections.
826
827 :param collections: The collections to check.
828 :param search_paths: Locations for the local collection lookup.
829 :param apis: A list of GalaxyAPIs to query when searching for a collection.
830 :param ignore_errors: Whether to ignore any errors when verifying the collection.
831 :param local_verify_only: When True, skip downloads and only verify local manifests.
832 :param artifacts_manager: Artifacts manager.
833 :return: list of CollectionVerifyResult objects describing the results of each collection verification
834 """
835 results = [] # type: list[CollectionVerifyResult]
836
837 api_proxy = MultiGalaxyAPIProxy(apis, artifacts_manager)
838
839 with _display_progress():
840 for collection in collections:
841 try:
842 if collection.is_concrete_artifact:
843 raise AnsibleError(
844 message="'{coll_type!s}' type is not supported. "
845 'The format namespace.name is expected.'.
846 format(coll_type=collection.type)
847 )
848
849 # NOTE: Verify local collection exists before
850 # NOTE: downloading its source artifact from
851 # NOTE: a galaxy server.
852 default_err = 'Collection %s is not installed in any of the collection paths.' % collection.fqcn
853 for search_path in search_paths:
854 b_search_path = to_bytes(
855 os.path.join(
856 search_path,
857 collection.namespace, collection.name,
858 ),
859 errors='surrogate_or_strict',
860 )
861 if not os.path.isdir(b_search_path):
862 continue
863 if not _is_installed_collection_dir(b_search_path):
864 default_err = (
865 "Collection %s does not have a MANIFEST.json. "
866 "A MANIFEST.json is expected if the collection has been built "
867 "and installed via ansible-galaxy" % collection.fqcn
868 )
869 continue
870
871 local_collection = Candidate.from_dir_path(
872 b_search_path, artifacts_manager,
873 )
874
875 if local_collection.fqcn != collection.fqcn:
876 default_err = f"Collection at '{to_text(local_collection.src)}' documents incorrect FQCN '{local_collection.fqcn}'"
877 continue
878
879 supplemental_signatures = [
880 get_signature_from_source(source, display)
881 for source in collection.signature_sources or []
882 ]
883 local_collection = Candidate(
884 local_collection.fqcn,
885 local_collection.ver,
886 local_collection.src,
887 local_collection.type,
888 signatures=frozenset(supplemental_signatures),
889 )
890
891 break
892 else:
893 raise AnsibleError(message=default_err)
894
895 if local_verify_only:
896 remote_collection = None
897 else:
898 signatures = api_proxy.get_signatures(local_collection)
899 signatures.extend([
900 get_signature_from_source(source, display)
901 for source in collection.signature_sources or []
902 ])
903
904 remote_collection = Candidate(
905 collection.fqcn,
906 collection.ver if collection.ver != '*'
907 else local_collection.ver,
908 None, 'galaxy',
909 frozenset(signatures),
910 )
911
912 # Download collection on a galaxy server for comparison
913 try:
914 # NOTE: If there are no signatures, trigger the lookup. If found,
915 # NOTE: it'll cache download URL and token in artifact manager.
916 # NOTE: If there are no Galaxy server signatures, only user-provided signature URLs,
917 # NOTE: those alone validate the MANIFEST.json and the remote collection is not downloaded.
918 # NOTE: The remote MANIFEST.json is only used in verification if there are no signatures.
919 if artifacts_manager.keyring is None or not signatures:
920 api_proxy.get_collection_version_metadata(
921 remote_collection,
922 )
923 except AnsibleError as e: # FIXME: does this actually emit any errors?
924 # FIXME: extract the actual message and adjust this:
925 expected_error_msg = (
926 'Failed to find collection {coll.fqcn!s}:{coll.ver!s}'.
927 format(coll=collection)
928 )
929 if e.message == expected_error_msg:
930 raise AnsibleError(
931 'Failed to find remote collection '
932 "'{coll!s}' on any of the galaxy servers".
933 format(coll=collection)
934 )
935 raise
936
937 result = verify_local_collection(local_collection, remote_collection, artifacts_manager)
938
939 results.append(result)
940
941 except AnsibleError as err:
942 if ignore_errors:
943 display.warning(
944 "Failed to verify collection '{coll!s}' but skipping "
945 'due to --ignore-errors being set. '
946 'Error: {err!s}'.
947 format(coll=collection, err=to_text(err)),
948 )
949 else:
950 raise
951
952 return results
953
954
955 @contextmanager
956 def _tempdir():
957 b_temp_path = tempfile.mkdtemp(dir=to_bytes(C.DEFAULT_LOCAL_TMP, errors='surrogate_or_strict'))
958 try:
959 yield b_temp_path
960 finally:
961 shutil.rmtree(b_temp_path)
962
963
964 @contextmanager
965 def _display_progress(msg=None):
966 config_display = C.GALAXY_DISPLAY_PROGRESS
967 display_wheel = sys.stdout.isatty() if config_display is None else config_display
968
969 global display
970 if msg is not None:
971 display.display(msg)
972
973 if not display_wheel:
974 yield
975 return
976
977 def progress(display_queue, actual_display):
978 actual_display.debug("Starting display_progress display thread")
979 t = threading.current_thread()
980
981 while True:
982 for c in "|/-\\":
983 actual_display.display(c + "\b", newline=False)
984 time.sleep(0.1)
985
986 # Display a message from the main thread
987 while True:
988 try:
989 method, args, kwargs = display_queue.get(block=False, timeout=0.1)
990 except queue.Empty:
991 break
992 else:
993 func = getattr(actual_display, method)
994 func(*args, **kwargs)
995
996 if getattr(t, "finish", False):
997 actual_display.debug("Received end signal for display_progress display thread")
998 return
999
1000 class DisplayThread(object):
1001
1002 def __init__(self, display_queue):
1003 self.display_queue = display_queue
1004
1005 def __getattr__(self, attr):
1006 def call_display(*args, **kwargs):
1007 self.display_queue.put((attr, args, kwargs))
1008
1009 return call_display
1010
1011 # Temporary override the global display class with our own which add the calls to a queue for the thread to call.
1012 old_display = display
1013 try:
1014 display_queue = queue.Queue()
1015 display = DisplayThread(display_queue)
1016 t = threading.Thread(target=progress, args=(display_queue, old_display))
1017 t.daemon = True
1018 t.start()
1019
1020 try:
1021 yield
1022 finally:
1023 t.finish = True
1024 t.join()
1025 except Exception:
1026 # The exception is re-raised so we can sure the thread is finished and not using the display anymore
1027 raise
1028 finally:
1029 display = old_display
1030
1031
1032 def _verify_file_hash(b_path, filename, expected_hash, error_queue):
1033 b_file_path = to_bytes(os.path.join(to_text(b_path), filename), errors='surrogate_or_strict')
1034
1035 if not os.path.isfile(b_file_path):
1036 actual_hash = None
1037 else:
1038 with open(b_file_path, mode='rb') as file_object:
1039 actual_hash = _consume_file(file_object)
1040
1041 if expected_hash != actual_hash:
1042 error_queue.append(ModifiedContent(filename=filename, expected=expected_hash, installed=actual_hash))
1043
1044
1045 def _make_manifest():
1046 return {
1047 'files': [
1048 {
1049 'name': '.',
1050 'ftype': 'dir',
1051 'chksum_type': None,
1052 'chksum_sha256': None,
1053 'format': MANIFEST_FORMAT,
1054 },
1055 ],
1056 'format': MANIFEST_FORMAT,
1057 }
1058
1059
1060 def _make_entry(name, ftype, chksum_type='sha256', chksum=None):
1061 return {
1062 'name': name,
1063 'ftype': ftype,
1064 'chksum_type': chksum_type if chksum else None,
1065 f'chksum_{chksum_type}': chksum,
1066 'format': MANIFEST_FORMAT
1067 }
1068
1069
1070 def _build_files_manifest(b_collection_path, namespace, name, ignore_patterns,
1071 manifest_control, license_file):
1072 # type: (bytes, str, str, list[str], dict[str, t.Any], t.Optional[str]) -> FilesManifestType
1073 if ignore_patterns and manifest_control is not Sentinel:
1074 raise AnsibleError('"build_ignore" and "manifest" are mutually exclusive')
1075
1076 if manifest_control is not Sentinel:
1077 manifest = _build_files_manifest_distlib(
1078 b_collection_path,
1079 namespace,
1080 name,
1081 manifest_control,
1082 license_file,
1083 )
1084 else:
1085 manifest = _build_files_manifest_walk(b_collection_path, namespace, name, ignore_patterns)
1086
1087 manifest['files'].sort(key=itemgetter('name'))
1088
1089 return manifest
1090
1091
1092 def _build_files_manifest_distlib(b_collection_path, namespace, name, manifest_control,
1093 license_file):
1094 # type: (bytes, str, str, dict[str, t.Any], t.Optional[str]) -> FilesManifestType
1095 if not HAS_DISTLIB:
1096 raise AnsibleError('Use of "manifest" requires the python "distlib" library')
1097
1098 if manifest_control is None:
1099 manifest_control = {}
1100
1101 try:
1102 control = ManifestControl(**manifest_control)
1103 except TypeError as ex:
1104 raise AnsibleError(f'Invalid "manifest" provided: {ex}')
1105
1106 if not is_sequence(control.directives):
1107 raise AnsibleError(f'"manifest.directives" must be a list, got: {control.directives.__class__.__name__}')
1108
1109 if not isinstance(control.omit_default_directives, bool):
1110 raise AnsibleError(
1111 '"manifest.omit_default_directives" is expected to be a boolean, got: '
1112 f'{control.omit_default_directives.__class__.__name__}'
1113 )
1114
1115 if control.omit_default_directives and not control.directives:
1116 raise AnsibleError(
1117 '"manifest.omit_default_directives" was set to True, but no directives were defined '
1118 'in "manifest.directives". This would produce an empty collection artifact.'
1119 )
1120
1121 directives = []
1122 if control.omit_default_directives:
1123 directives.extend(control.directives)
1124 else:
1125 directives.extend([
1126 'include meta/*.yml',
1127 'include *.txt *.md *.rst *.license COPYING LICENSE',
1128 'recursive-include .reuse **',
1129 'recursive-include LICENSES **',
1130 'recursive-include tests **',
1131 'recursive-include docs **.rst **.yml **.yaml **.json **.j2 **.txt **.license',
1132 'recursive-include roles **.yml **.yaml **.json **.j2 **.license',
1133 'recursive-include playbooks **.yml **.yaml **.json **.license',
1134 'recursive-include changelogs **.yml **.yaml **.license',
1135 'recursive-include plugins */**.py */**.license',
1136 ])
1137
1138 if license_file:
1139 directives.append(f'include {license_file}')
1140
1141 plugins = set(l.package.split('.')[-1] for d, l in get_all_plugin_loaders())
1142 for plugin in sorted(plugins):
1143 if plugin in ('modules', 'module_utils'):
1144 continue
1145 elif plugin in C.DOCUMENTABLE_PLUGINS:
1146 directives.append(
1147 f'recursive-include plugins/{plugin} **.yml **.yaml'
1148 )
1149
1150 directives.extend([
1151 'recursive-include plugins/modules **.ps1 **.yml **.yaml **.license',
1152 'recursive-include plugins/module_utils **.ps1 **.psm1 **.cs **.license',
1153 ])
1154
1155 directives.extend(control.directives)
1156
1157 directives.extend([
1158 f'exclude galaxy.yml galaxy.yaml MANIFEST.json FILES.json {namespace}-{name}-*.tar.gz',
1159 'recursive-exclude tests/output **',
1160 'global-exclude /.* /__pycache__ *.pyc *.pyo *.bak *~ *.swp',
1161 ])
1162
1163 display.vvv('Manifest Directives:')
1164 display.vvv(textwrap.indent('\n'.join(directives), ' '))
1165
1166 u_collection_path = to_text(b_collection_path, errors='surrogate_or_strict')
1167 m = Manifest(u_collection_path)
1168 for directive in directives:
1169 try:
1170 m.process_directive(directive)
1171 except DistlibException as e:
1172 raise AnsibleError(f'Invalid manifest directive: {e}')
1173 except Exception as e:
1174 raise AnsibleError(f'Unknown error processing manifest directive: {e}')
1175
1176 manifest = _make_manifest()
1177
1178 for abs_path in m.sorted(wantdirs=True):
1179 rel_path = os.path.relpath(abs_path, u_collection_path)
1180 if os.path.isdir(abs_path):
1181 manifest_entry = _make_entry(rel_path, 'dir')
1182 else:
1183 manifest_entry = _make_entry(
1184 rel_path,
1185 'file',
1186 chksum_type='sha256',
1187 chksum=secure_hash(abs_path, hash_func=sha256)
1188 )
1189
1190 manifest['files'].append(manifest_entry)
1191 return manifest
1192
1193
1194 def _build_files_manifest_walk(b_collection_path, namespace, name, ignore_patterns):
1195 # type: (bytes, str, str, list[str]) -> FilesManifestType
1196 # We always ignore .pyc and .retry files as well as some well known version control directories. The ignore
1197 # patterns can be extended by the build_ignore key in galaxy.yml
1198 b_ignore_patterns = [
1199 b'MANIFEST.json',
1200 b'FILES.json',
1201 b'galaxy.yml',
1202 b'galaxy.yaml',
1203 b'.git',
1204 b'*.pyc',
1205 b'*.retry',
1206 b'tests/output', # Ignore ansible-test result output directory.
1207 to_bytes('{0}-{1}-*.tar.gz'.format(namespace, name)), # Ignores previously built artifacts in the root dir.
1208 ]
1209 b_ignore_patterns += [to_bytes(p) for p in ignore_patterns]
1210 b_ignore_dirs = frozenset([b'CVS', b'.bzr', b'.hg', b'.git', b'.svn', b'__pycache__', b'.tox'])
1211
1212 manifest = _make_manifest()
1213
1214 def _discover_relative_base_directory(b_path: bytes, b_top_level_dir: bytes) -> bytes:
1215 if b_path == b_top_level_dir:
1216 return b''
1217 common_prefix = os.path.commonpath((b_top_level_dir, b_path))
1218 b_rel_base_dir = os.path.relpath(b_path, common_prefix)
1219 return b_rel_base_dir.lstrip(os.path.sep.encode())
1220
1221 def _walk(b_path, b_top_level_dir):
1222 b_rel_base_dir = _discover_relative_base_directory(b_path, b_top_level_dir)
1223 for b_item in os.listdir(b_path):
1224 b_abs_path = os.path.join(b_path, b_item)
1225 b_rel_path = os.path.join(b_rel_base_dir, b_item)
1226 rel_path = to_text(b_rel_path, errors='surrogate_or_strict')
1227
1228 if os.path.isdir(b_abs_path):
1229 if any(b_item == b_path for b_path in b_ignore_dirs) or \
1230 any(fnmatch.fnmatch(b_rel_path, b_pattern) for b_pattern in b_ignore_patterns):
1231 display.vvv("Skipping '%s' for collection build" % to_text(b_abs_path))
1232 continue
1233
1234 if os.path.islink(b_abs_path):
1235 b_link_target = os.path.realpath(b_abs_path)
1236
1237 if not _is_child_path(b_link_target, b_top_level_dir):
1238 display.warning("Skipping '%s' as it is a symbolic link to a directory outside the collection"
1239 % to_text(b_abs_path))
1240 continue
1241
1242 manifest['files'].append(_make_entry(rel_path, 'dir'))
1243
1244 if not os.path.islink(b_abs_path):
1245 _walk(b_abs_path, b_top_level_dir)
1246 else:
1247 if any(fnmatch.fnmatch(b_rel_path, b_pattern) for b_pattern in b_ignore_patterns):
1248 display.vvv("Skipping '%s' for collection build" % to_text(b_abs_path))
1249 continue
1250
1251 # Handling of file symlinks occur in _build_collection_tar, the manifest for a symlink is the same for
1252 # a normal file.
1253 manifest['files'].append(
1254 _make_entry(
1255 rel_path,
1256 'file',
1257 chksum_type='sha256',
1258 chksum=secure_hash(b_abs_path, hash_func=sha256)
1259 )
1260 )
1261
1262 _walk(b_collection_path, b_collection_path)
1263
1264 return manifest
1265
1266
1267 # FIXME: accept a dict produced from `galaxy.yml` instead of separate args
1268 def _build_manifest(namespace, name, version, authors, readme, tags, description, license_file,
1269 dependencies, repository, documentation, homepage, issues, **kwargs):
1270 manifest = {
1271 'collection_info': {
1272 'namespace': namespace,
1273 'name': name,
1274 'version': version,
1275 'authors': authors,
1276 'readme': readme,
1277 'tags': tags,
1278 'description': description,
1279 'license': kwargs['license'],
1280 'license_file': license_file or None, # Handle galaxy.yml having an empty string (None)
1281 'dependencies': dependencies,
1282 'repository': repository,
1283 'documentation': documentation,
1284 'homepage': homepage,
1285 'issues': issues,
1286 },
1287 'file_manifest_file': {
1288 'name': 'FILES.json',
1289 'ftype': 'file',
1290 'chksum_type': 'sha256',
1291 'chksum_sha256': None, # Filled out in _build_collection_tar
1292 'format': MANIFEST_FORMAT
1293 },
1294 'format': MANIFEST_FORMAT,
1295 }
1296
1297 return manifest
1298
1299
1300 def _build_collection_tar(
1301 b_collection_path, # type: bytes
1302 b_tar_path, # type: bytes
1303 collection_manifest, # type: CollectionManifestType
1304 file_manifest, # type: FilesManifestType
1305 ): # type: (...) -> str
1306 """Build a tar.gz collection artifact from the manifest data."""
1307 files_manifest_json = to_bytes(json.dumps(file_manifest, indent=True, sort_keys=True), errors='surrogate_or_strict')
1308 collection_manifest['file_manifest_file']['chksum_sha256'] = secure_hash_s(files_manifest_json, hash_func=sha256)
1309 collection_manifest_json = to_bytes(json.dumps(collection_manifest, indent=True), errors='surrogate_or_strict')
1310
1311 with _tempdir() as b_temp_path:
1312 b_tar_filepath = os.path.join(b_temp_path, os.path.basename(b_tar_path))
1313
1314 with tarfile.open(b_tar_filepath, mode='w:gz') as tar_file:
1315 # Add the MANIFEST.json and FILES.json file to the archive
1316 for name, b in [(MANIFEST_FILENAME, collection_manifest_json), ('FILES.json', files_manifest_json)]:
1317 b_io = BytesIO(b)
1318 tar_info = tarfile.TarInfo(name)
1319 tar_info.size = len(b)
1320 tar_info.mtime = int(time.time())
1321 tar_info.mode = S_IRWU_RG_RO
1322 tar_file.addfile(tarinfo=tar_info, fileobj=b_io)
1323
1324 for file_info in file_manifest['files']: # type: ignore[union-attr]
1325 if file_info['name'] == '.':
1326 continue
1327
1328 # arcname expects a native string, cannot be bytes
1329 filename = to_native(file_info['name'], errors='surrogate_or_strict')
1330 b_src_path = os.path.join(b_collection_path, to_bytes(filename, errors='surrogate_or_strict'))
1331
1332 def reset_stat(tarinfo):
1333 if tarinfo.type != tarfile.SYMTYPE:
1334 existing_is_exec = tarinfo.mode & stat.S_IXUSR
1335 tarinfo.mode = S_IRWXU_RXG_RXO if existing_is_exec or tarinfo.isdir() else S_IRWU_RG_RO
1336 tarinfo.uid = tarinfo.gid = 0
1337 tarinfo.uname = tarinfo.gname = ''
1338
1339 return tarinfo
1340
1341 if os.path.islink(b_src_path):
1342 b_link_target = os.path.realpath(b_src_path)
1343 if not os.path.exists(b_link_target):
1344 raise AnsibleError(f"Failed to find the target path '{to_native(b_link_target)}' for the symlink '{to_native(b_src_path)}'.")
1345 if _is_child_path(b_link_target, b_collection_path):
1346 b_rel_path = os.path.relpath(b_link_target, start=os.path.dirname(b_src_path))
1347
1348 tar_info = tarfile.TarInfo(filename)
1349 tar_info.type = tarfile.SYMTYPE
1350 tar_info.linkname = to_native(b_rel_path, errors='surrogate_or_strict')
1351 tar_info = reset_stat(tar_info)
1352 tar_file.addfile(tarinfo=tar_info)
1353
1354 continue
1355
1356 # Dealing with a normal file, just add it by name.
1357 tar_file.add(
1358 to_native(os.path.realpath(b_src_path)),
1359 arcname=filename,
1360 recursive=False,
1361 filter=reset_stat,
1362 )
1363
1364 shutil.copy(to_native(b_tar_filepath), to_native(b_tar_path))
1365 collection_name = "%s.%s" % (collection_manifest['collection_info']['namespace'],
1366 collection_manifest['collection_info']['name'])
1367 tar_path = to_text(b_tar_path)
1368 display.display(u'Created collection for %s at %s' % (collection_name, tar_path))
1369 return tar_path
1370
1371
1372 def _build_collection_dir(b_collection_path, b_collection_output, collection_manifest, file_manifest):
1373 """Build a collection directory from the manifest data.
1374
1375 This should follow the same pattern as _build_collection_tar.
1376 """
1377 os.makedirs(b_collection_output, mode=S_IRWXU_RXG_RXO)
1378
1379 files_manifest_json = to_bytes(json.dumps(file_manifest, indent=True, sort_keys=True), errors='surrogate_or_strict')
1380 collection_manifest['file_manifest_file']['chksum_sha256'] = secure_hash_s(files_manifest_json, hash_func=sha256)
1381 collection_manifest_json = to_bytes(json.dumps(collection_manifest, indent=True), errors='surrogate_or_strict')
1382
1383 # Write contents to the files
1384 for name, b in [(MANIFEST_FILENAME, collection_manifest_json), ('FILES.json', files_manifest_json)]:
1385 b_path = os.path.join(b_collection_output, to_bytes(name, errors='surrogate_or_strict'))
1386 with open(b_path, 'wb') as file_obj, BytesIO(b) as b_io:
1387 shutil.copyfileobj(b_io, file_obj)
1388
1389 os.chmod(b_path, S_IRWU_RG_RO)
1390
1391 base_directories = []
1392 for file_info in file_manifest['files']:
1393 if file_info['name'] == '.':
1394 continue
1395
1396 src_file = os.path.join(b_collection_path, to_bytes(file_info['name'], errors='surrogate_or_strict'))
1397 dest_file = os.path.join(b_collection_output, to_bytes(file_info['name'], errors='surrogate_or_strict'))
1398
1399 existing_is_exec = os.stat(src_file, follow_symlinks=False).st_mode & stat.S_IXUSR
1400 mode = S_IRWXU_RXG_RXO if existing_is_exec else S_IRWU_RG_RO
1401
1402 # ensure symlinks to dirs are not translated to empty dirs
1403 if os.path.isdir(src_file) and not os.path.islink(src_file):
1404 mode = S_IRWXU_RXG_RXO
1405 base_directories.append(src_file)
1406 os.mkdir(dest_file, mode)
1407 else:
1408 # do not follow symlinks to ensure the original link is used
1409 shutil.copyfile(src_file, dest_file, follow_symlinks=False)
1410
1411 # avoid setting specific permission on symlinks since it does not
1412 # support avoid following symlinks and will thrown an exception if the
1413 # symlink target does not exist
1414 if not os.path.islink(dest_file):
1415 os.chmod(dest_file, mode)
1416
1417 collection_output = to_text(b_collection_output)
1418 return collection_output
1419
1420
1421 def _normalize_collection_path(path):
1422 str_path = path.as_posix() if isinstance(path, pathlib.Path) else path
1423 return pathlib.Path(
1424 # This is annoying, but GalaxyCLI._resolve_path did it
1425 os.path.expandvars(str_path)
1426 ).expanduser().absolute()
1427
1428
1429 def find_existing_collections(path_filter, artifacts_manager, namespace_filter=None, collection_filter=None, dedupe=True):
1430 """Locate all collections under a given path.
1431
1432 :param path: Collection dirs layout search path.
1433 :param artifacts_manager: Artifacts manager.
1434 """
1435 if path_filter and not is_sequence(path_filter):
1436 path_filter = [path_filter]
1437 if namespace_filter and not is_sequence(namespace_filter):
1438 namespace_filter = [namespace_filter]
1439 if collection_filter and not is_sequence(collection_filter):
1440 collection_filter = [collection_filter]
1441
1442 paths = set()
1443 for path in files('ansible_collections').glob('*/*/'):
1444 path = _normalize_collection_path(path)
1445 if not path.is_dir():
1446 continue
1447 if path_filter:
1448 for pf in path_filter:
1449 try:
1450 path.relative_to(_normalize_collection_path(pf))
1451 except ValueError:
1452 continue
1453 break
1454 else:
1455 continue
1456 paths.add(path)
1457
1458 seen = set()
1459 for path in paths:
1460 namespace = path.parent.name
1461 name = path.name
1462 if namespace_filter and namespace not in namespace_filter:
1463 continue
1464 if collection_filter and name not in collection_filter:
1465 continue
1466
1467 if dedupe:
1468 try:
1469 collection_path = files(f'ansible_collections.{namespace}.{name}')
1470 except ImportError:
1471 continue
1472 if collection_path in seen:
1473 continue
1474 seen.add(collection_path)
1475 else:
1476 collection_path = path
1477
1478 b_collection_path = to_bytes(collection_path.as_posix())
1479
1480 try:
1481 req = Candidate.from_dir_path_as_unknown(b_collection_path, artifacts_manager)
1482 except ValueError as val_err:
1483 display.warning(f'{val_err}')
1484 continue
1485
1486 if req.fqcn != '.'.join(pathlib.Path(to_text(req.src)).parts[-2:]):
1487 display.warning(f"Collection at {to_text(req.src)} documents incorrect FQCN '{req.fqcn}'. Ignoring metadata.")
1488 req = Candidate.from_dir_path_implicit(b_collection_path)
1489
1490 display.vvv(
1491 u"Found installed collection {coll!s} at '{path!s}'".
1492 format(coll=to_text(req), path=to_text(req.src))
1493 )
1494 yield req
1495
1496
1497 def install(collection, path, artifacts_manager): # FIXME: mv to dataclasses?
1498 # type: (Candidate, str, ConcreteArtifactsManager) -> None
1499 """Install a collection under a given path.
1500
1501 :param collection: Collection to be installed.
1502 :param path: Collection dirs layout path.
1503 :param artifacts_manager: Artifacts manager.
1504 """
1505 b_artifact_path = artifacts_manager.get_artifact_path_from_unknown(collection)
1506
1507 collection_path = os.path.join(path, collection.namespace, collection.name)
1508 b_collection_path = to_bytes(collection_path, errors='surrogate_or_strict')
1509 display.display(
1510 u"Installing '{coll!s}' to '{path!s}'".
1511 format(coll=to_text(collection), path=collection_path),
1512 )
1513
1514 if os.path.exists(b_collection_path):
1515 shutil.rmtree(b_collection_path)
1516
1517 if collection.is_dir:
1518 install_src(collection, b_artifact_path, b_collection_path, artifacts_manager)
1519 else:
1520 install_artifact(
1521 b_artifact_path,
1522 b_collection_path,
1523 artifacts_manager._b_working_directory,
1524 collection.signatures,
1525 artifacts_manager.keyring,
1526 artifacts_manager.required_successful_signature_count,
1527 artifacts_manager.ignore_signature_errors,
1528 )
1529 remove_source_metadata(collection, b_collection_path)
1530 if (collection.is_online_index_pointer and isinstance(collection.src, GalaxyAPI)):
1531 write_source_metadata(
1532 collection,
1533 b_collection_path,
1534 artifacts_manager
1535 )
1536
1537 display.display(
1538 '{coll!s} was installed successfully'.
1539 format(coll=to_text(collection)),
1540 )
1541
1542
1543 def write_source_metadata(collection, b_collection_path, artifacts_manager):
1544 # type: (Candidate, bytes, ConcreteArtifactsManager) -> None
1545 source_data = artifacts_manager.get_galaxy_artifact_source_info(collection)
1546
1547 b_yaml_source_data = to_bytes(yaml_dump(source_data), errors='surrogate_or_strict')
1548 b_info_dest = collection.construct_galaxy_info_path(b_collection_path)
1549 b_info_dir = os.path.split(b_info_dest)[0]
1550
1551 if os.path.exists(b_info_dir):
1552 shutil.rmtree(b_info_dir)
1553
1554 try:
1555 os.mkdir(b_info_dir, mode=S_IRWXU_RXG_RXO)
1556 with open(b_info_dest, mode='w+b') as fd:
1557 fd.write(b_yaml_source_data)
1558 os.chmod(b_info_dest, S_IRWU_RG_RO)
1559 except Exception:
1560 # Ensure we don't leave the dir behind in case of a failure.
1561 if os.path.isdir(b_info_dir):
1562 shutil.rmtree(b_info_dir)
1563 raise
1564
1565
1566 def remove_source_metadata(collection, b_collection_path):
1567 pattern = f"{collection.namespace}.{collection.name}-*.info"
1568 info_path = os.path.join(
1569 b_collection_path,
1570 b'../../',
1571 to_bytes(pattern, errors='surrogate_or_strict')
1572 )
1573 if (outdated_info := glob.glob(info_path)):
1574 display.vvvv(f"Removing {pattern} metadata from previous installations")
1575 for info_dir in outdated_info:
1576 try:
1577 shutil.rmtree(info_dir)
1578 except Exception:
1579 pass
1580
1581
1582 def verify_artifact_manifest(manifest_file, signatures, keyring, required_signature_count, ignore_signature_errors):
1583 # type: (str, list[str], str, str, list[str]) -> None
1584 failed_verify = False
1585 coll_path_parts = to_text(manifest_file, errors='surrogate_or_strict').split(os.path.sep)
1586 collection_name = '%s.%s' % (coll_path_parts[-3], coll_path_parts[-2]) # get 'ns' and 'coll' from /path/to/ns/coll/MANIFEST.json
1587 if not verify_file_signatures(collection_name, manifest_file, signatures, keyring, required_signature_count, ignore_signature_errors):
1588 raise AnsibleError(f"Not installing {collection_name} because GnuPG signature verification failed.")
1589 display.vvvv(f"GnuPG signature verification succeeded for {collection_name}")
1590
1591
1592 def install_artifact(b_coll_targz_path, b_collection_path, b_temp_path, signatures, keyring, required_signature_count, ignore_signature_errors):
1593 """Install a collection from tarball under a given path.
1594
1595 :param b_coll_targz_path: Collection tarball to be installed.
1596 :param b_collection_path: Collection dirs layout path.
1597 :param b_temp_path: Temporary dir path.
1598 :param signatures: frozenset of signatures to verify the MANIFEST.json
1599 :param keyring: The keyring used during GPG verification
1600 :param required_signature_count: The number of signatures that must successfully verify the collection
1601 :param ignore_signature_errors: GPG errors to ignore during signature verification
1602 """
1603 try:
1604 with tarfile.open(b_coll_targz_path, mode='r') as collection_tar:
1605 # Verify the signature on the MANIFEST.json before extracting anything else
1606 _extract_tar_file(collection_tar, MANIFEST_FILENAME, b_collection_path, b_temp_path)
1607
1608 if keyring is not None:
1609 manifest_file = os.path.join(to_text(b_collection_path, errors='surrogate_or_strict'), MANIFEST_FILENAME)
1610 verify_artifact_manifest(manifest_file, signatures, keyring, required_signature_count, ignore_signature_errors)
1611
1612 files_member_obj = collection_tar.getmember('FILES.json')
1613 with _tarfile_extract(collection_tar, files_member_obj) as (dummy, files_obj):
1614 files = json.loads(to_text(files_obj.read(), errors='surrogate_or_strict'))
1615
1616 _extract_tar_file(collection_tar, 'FILES.json', b_collection_path, b_temp_path)
1617
1618 for file_info in files['files']:
1619 file_name = file_info['name']
1620 if file_name == '.':
1621 continue
1622
1623 if file_info['ftype'] == 'file':
1624 _extract_tar_file(collection_tar, file_name, b_collection_path, b_temp_path,
1625 expected_hash=file_info['chksum_sha256'])
1626
1627 else:
1628 _extract_tar_dir(collection_tar, file_name, b_collection_path)
1629
1630 except Exception:
1631 # Ensure we don't leave the dir behind in case of a failure.
1632 shutil.rmtree(b_collection_path)
1633
1634 b_namespace_path = os.path.dirname(b_collection_path)
1635 if not os.listdir(b_namespace_path):
1636 os.rmdir(b_namespace_path)
1637
1638 raise
1639
1640
1641 def install_src(collection, b_collection_path, b_collection_output_path, artifacts_manager):
1642 r"""Install the collection from source control into given dir.
1643
1644 Generates the Ansible collection artifact data from a galaxy.yml and
1645 installs the artifact to a directory.
1646 This should follow the same pattern as build_collection, but instead
1647 of creating an artifact, install it.
1648
1649 :param collection: Collection to be installed.
1650 :param b_collection_path: Collection dirs layout path.
1651 :param b_collection_output_path: The installation directory for the \
1652 collection artifact.
1653 :param artifacts_manager: Artifacts manager.
1654
1655 :raises AnsibleError: If no collection metadata found.
1656 """
1657 collection_meta = artifacts_manager.get_direct_collection_meta(collection)
1658
1659 if 'build_ignore' not in collection_meta: # installed collection, not src
1660 # FIXME: optimize this? use a different process? copy instead of build?
1661 collection_meta['build_ignore'] = []
1662 collection_meta['manifest'] = Sentinel
1663 collection_manifest = _build_manifest(**collection_meta)
1664 file_manifest = _build_files_manifest(
1665 b_collection_path,
1666 collection_meta['namespace'], collection_meta['name'],
1667 collection_meta['build_ignore'],
1668 collection_meta['manifest'],
1669 collection_meta['license_file'],
1670 )
1671
1672 collection_output_path = _build_collection_dir(
1673 b_collection_path, b_collection_output_path,
1674 collection_manifest, file_manifest,
1675 )
1676
1677 display.display(
1678 'Created collection for {coll!s} at {path!s}'.
1679 format(coll=collection, path=collection_output_path)
1680 )
1681
1682
1683 def _extract_tar_dir(tar, dirname, b_dest):
1684 """ Extracts a directory from a collection tar. """
1685 dirname = to_native(dirname, errors='surrogate_or_strict')
1686
1687 try:
1688 tar_member = tar.getmember(dirname)
1689 except KeyError:
1690 raise AnsibleError("Unable to extract '%s' from collection" % dirname)
1691
1692 b_dir_path = os.path.join(b_dest, to_bytes(dirname, errors='surrogate_or_strict'))
1693
1694 b_parent_path = os.path.dirname(b_dir_path)
1695 os.makedirs(b_parent_path, mode=S_IRWXU_RXG_RXO, exist_ok=True)
1696
1697 if tar_member.type == tarfile.SYMTYPE:
1698 b_link_path = to_bytes(tar_member.linkname, errors='surrogate_or_strict')
1699 if not _is_child_path(b_link_path, b_dest, link_name=b_dir_path):
1700 raise AnsibleError("Cannot extract symlink '%s' in collection: path points to location outside of "
1701 "collection '%s'" % (to_native(dirname), b_link_path))
1702
1703 os.symlink(b_link_path, b_dir_path)
1704
1705 else:
1706 if not os.path.isdir(b_dir_path):
1707 os.mkdir(b_dir_path, S_IRWXU_RXG_RXO)
1708
1709
1710 def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None):
1711 """ Extracts a file from a collection tar. """
1712 with _get_tar_file_member(tar, filename) as (tar_member, tar_obj):
1713 if tar_member.type == tarfile.SYMTYPE:
1714 actual_hash = _consume_file(tar_obj)
1715
1716 else:
1717 with tempfile.NamedTemporaryFile(dir=b_temp_path, delete=False) as tmpfile_obj:
1718 actual_hash = _consume_file(tar_obj, tmpfile_obj)
1719
1720 if expected_hash and actual_hash != expected_hash:
1721 raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'"
1722 % (to_native(filename, errors='surrogate_or_strict'), to_native(tar.name)))
1723
1724 b_dest_filepath = os.path.abspath(os.path.join(b_dest, to_bytes(filename, errors='surrogate_or_strict')))
1725 b_parent_dir = os.path.dirname(b_dest_filepath)
1726 if not _is_child_path(b_parent_dir, b_dest):
1727 raise AnsibleError("Cannot extract tar entry '%s' as it will be placed outside the collection directory"
1728 % to_native(filename, errors='surrogate_or_strict'))
1729
1730 if not os.path.exists(b_parent_dir):
1731 # Seems like Galaxy does not validate if all file entries have a corresponding dir ftype entry. This check
1732 # makes sure we create the parent directory even if it wasn't set in the metadata.
1733 os.makedirs(b_parent_dir, mode=S_IRWXU_RXG_RXO)
1734
1735 if tar_member.type == tarfile.SYMTYPE:
1736 b_link_path = to_bytes(tar_member.linkname, errors='surrogate_or_strict')
1737 if not _is_child_path(b_link_path, b_dest, link_name=b_dest_filepath):
1738 raise AnsibleError("Cannot extract symlink '%s' in collection: path points to location outside of "
1739 "collection '%s'" % (to_native(filename), b_link_path))
1740
1741 os.symlink(b_link_path, b_dest_filepath)
1742
1743 else:
1744 shutil.move(to_bytes(tmpfile_obj.name, errors='surrogate_or_strict'), b_dest_filepath)
1745
1746 # Default to rw-r--r-- and only add execute if the tar file has execute.
1747 tar_member = tar.getmember(to_native(filename, errors='surrogate_or_strict'))
1748 new_mode = S_IRWU_RG_RO
1749 if stat.S_IMODE(tar_member.mode) & stat.S_IXUSR:
1750 new_mode |= S_IXANY
1751
1752 os.chmod(b_dest_filepath, new_mode)
1753
1754
1755 def _get_tar_file_member(tar, filename):
1756 n_filename = to_native(filename, errors='surrogate_or_strict')
1757 try:
1758 member = tar.getmember(n_filename)
1759 except KeyError:
1760 raise AnsibleError("Collection tar at '%s' does not contain the expected file '%s'." % (
1761 to_native(tar.name),
1762 n_filename))
1763
1764 return _tarfile_extract(tar, member)
1765
1766
1767 def _get_json_from_tar_file(b_path, filename):
1768 file_contents = ''
1769
1770 with tarfile.open(b_path, mode='r') as collection_tar:
1771 with _get_tar_file_member(collection_tar, filename) as (dummy, tar_obj):
1772 bufsize = 65536
1773 data = tar_obj.read(bufsize)
1774 while data:
1775 file_contents += to_text(data)
1776 data = tar_obj.read(bufsize)
1777
1778 return json.loads(file_contents)
1779
1780
1781 def _get_tar_file_hash(b_path, filename):
1782 with tarfile.open(b_path, mode='r') as collection_tar:
1783 with _get_tar_file_member(collection_tar, filename) as (dummy, tar_obj):
1784 return _consume_file(tar_obj)
1785
1786
1787 def _get_file_hash(b_path, filename): # type: (bytes, str) -> str
1788 filepath = os.path.join(b_path, to_bytes(filename, errors='surrogate_or_strict'))
1789 with open(filepath, 'rb') as fp:
1790 return _consume_file(fp)
1791
1792
1793 def _is_child_path(path, parent_path, link_name=None):
1794 """ Checks that path is a path within the parent_path specified. """
1795 b_path = to_bytes(path, errors='surrogate_or_strict')
1796
1797 if link_name and not os.path.isabs(b_path):
1798 # If link_name is specified, path is the source of the link and we need to resolve the absolute path.
1799 b_link_dir = os.path.dirname(to_bytes(link_name, errors='surrogate_or_strict'))
1800 b_path = os.path.abspath(os.path.join(b_link_dir, b_path))
1801
1802 b_parent_path = to_bytes(parent_path, errors='surrogate_or_strict')
1803 return b_path == b_parent_path or b_path.startswith(b_parent_path + to_bytes(os.path.sep))
1804
1805
1806 def _resolve_depenency_map(
1807 requested_requirements, # type: t.Iterable[Requirement]
1808 galaxy_apis, # type: t.Iterable[GalaxyAPI]
1809 concrete_artifacts_manager, # type: ConcreteArtifactsManager
1810 preferred_candidates, # type: t.Iterable[Candidate] | None
1811 no_deps, # type: bool
1812 allow_pre_release, # type: bool
1813 upgrade, # type: bool
1814 include_signatures, # type: bool
1815 offline, # type: bool
1816 ): # type: (...) -> dict[str, Candidate]
1817 """Return the resolved dependency map."""
1818 if not HAS_RESOLVELIB:
1819 raise AnsibleError("Failed to import resolvelib, check that a supported version is installed")
1820 if not HAS_PACKAGING:
1821 raise AnsibleError("Failed to import packaging, check that a supported version is installed")
1822
1823 req = None
1824
1825 try:
1826 dist = distribution('ansible-core')
1827 except Exception:
1828 pass
1829 else:
1830 req = next((rr for r in (dist.requires or []) if (rr := PkgReq(r)).name == 'resolvelib'), None)
1831 finally:
1832 if req is None:
1833 # TODO: replace the hardcoded versions with a warning if the dist info is missing
1834 # display.warning("Unable to find 'ansible-core' distribution requirements to verify the resolvelib version is supported.")
1835 if not RESOLVELIB_LOWERBOUND <= RESOLVELIB_VERSION < RESOLVELIB_UPPERBOUND:
1836 raise AnsibleError(
1837 f"ansible-galaxy requires resolvelib<{RESOLVELIB_UPPERBOUND.vstring},>={RESOLVELIB_LOWERBOUND.vstring}"
1838 )
1839 elif not req.specifier.contains(RESOLVELIB_VERSION.vstring):
1840 raise AnsibleError(f"ansible-galaxy requires {req.name}{req.specifier}")
1841
1842 pre_release_hint = '' if allow_pre_release else (
1843 'Hint: Pre-releases hosted on Galaxy or Automation Hub are not '
1844 'installed by default unless a specific version is requested. '
1845 'To enable pre-releases globally, use --pre.'
1846 )
1847 requires_ansible_hint = '' if C.COLLECTIONS_ON_ANSIBLE_VERSION_MISMATCH == 'ignore' else (
1848 'Hint: To disregard whether the collection supports the current version of '
1849 'ansible-core, configure COLLECTIONS_ON_ANSIBLE_VERSION_MISMATCH as "ignore".'
1850 )
1851
1852 collection_dep_resolver = build_collection_dependency_resolver(
1853 galaxy_apis=galaxy_apis,
1854 concrete_artifacts_manager=concrete_artifacts_manager,
1855 preferred_candidates=preferred_candidates,
1856 with_deps=not no_deps,
1857 with_pre_releases=allow_pre_release,
1858 upgrade=upgrade,
1859 include_signatures=include_signatures,
1860 offline=offline,
1861 )
1862 try:
1863 return t.cast(
1864 dict[str, Candidate],
1865 collection_dep_resolver.resolve(
1866 requested_requirements,
1867 max_rounds=2000000, # NOTE: same constant pip uses
1868 ).mapping,
1869 )
1870 except CollectionDependencyResolutionImpossible as dep_exc:
1871 conflict_causes = []
1872 for req_inf in dep_exc.causes:
1873 if req_inf.requirement.type == "requires_ansible":
1874 if req_inf.requirement.has_candidate:
1875 continue
1876 collection = str(req_inf.parent)
1877 parents = [str(r._parent) for r in req_inf.parent._requirements if r._parent is not None]
1878 if not parents:
1879 dep_origin = 'direct request'
1880 else:
1881 dep_origin = f'dependency of {", ".join(parents)}'
1882 else:
1883 collection = str(req_inf.requirement)
1884 dep_origin = 'direct request' if req_inf.parent is None else f'dependency of {req_inf.parent!s}'
1885
1886 cause = f"* {collection} ({dep_origin})"
1887 if req_inf.requirement.type == "requires_ansible":
1888 cause += f" requires {req_inf.requirement.fqcn!s} {req_inf.requirement.ver!s}"
1889
1890 conflict_causes.append(cause)
1891
1892 error_msg_lines = list(chain(
1893 (
1894 'Failed to resolve the requested '
1895 'dependencies map. Could not satisfy the following '
1896 'requirements:',
1897 ),
1898 conflict_causes,
1899 ))
1900 if any(req_inf.requirement.type == "requires_ansible" for req_inf in dep_exc.causes):
1901 dep_exc = None
1902 error_msg_lines.append(requires_ansible_hint)
1903 error_msg_lines.append(pre_release_hint)
1904 raise AnsibleError('\n'.join(error_msg_lines)) from dep_exc
1905 except CollectionDependencyInconsistentCandidate as dep_exc:
1906 parents = [
1907 str(p) for p in dep_exc.criterion.iter_parent()
1908 if p is not None
1909 ]
1910
1911 error_msg_lines = [
1912 (
1913 'Failed to resolve the requested dependencies map. '
1914 'Got the candidate {req.fqcn!s}:{req.ver!s} ({dep_origin!s}) '
1915 'which didn\'t satisfy all of the following requirements:'.
1916 format(
1917 req=dep_exc.candidate,
1918 dep_origin='direct request'
1919 if not parents else 'dependency of {parent!s}'.
1920 format(parent=', '.join(parents))
1921 )
1922 )
1923 ]
1924
1925 for req in dep_exc.criterion.iter_requirement():
1926 error_msg_lines.append(
1927 f'* {req.fqcn!s}:{req.ver!s}'
1928 )
1929 error_msg_lines.append(pre_release_hint)
1930
1931 raise AnsibleError('\n'.join(error_msg_lines)) from dep_exc
1932 except ValueError as exc:
1933 raise AnsibleError(to_native(exc)) from exc