Debian Codegraph @

lib/ansible/galaxy/collection/concrete_artifact_manager.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 """Concrete collection candidate management helper module."""
5
6 from __future__ import annotations
7
8 import json
9 import os
10 import tarfile
11 import subprocess
12 import typing as t
13 import yaml
14
15 from collections.abc import Mapping
16 from contextlib import contextmanager, suppress
17 from functools import cache
18 from hashlib import sha256
19 from pathlib import Path
20 from http.client import IncompleteRead, HTTPResponse
21 from urllib.error import URLError
22 from urllib.parse import urldefrag
23 from shutil import rmtree
24 from tempfile import mkdtemp
25
26 if t.TYPE_CHECKING:
27 from ansible.galaxy.dependency_resolution.dataclasses import (
28 Candidate, Collection, Requirement,
29 )
30 from ansible.galaxy.token import GalaxyToken
31
32 from ansible import context
33 from ansible.errors import AnsibleError
34 from ansible.galaxy import get_collections_galaxy_meta_info
35 from ansible.galaxy.api import should_retry_error, CollectionVersionMetadata, GalaxyAPI
36 from ansible.galaxy.dependency_resolution.dataclasses import _GALAXY_YAML
37 from ansible.galaxy.user_agent import user_agent
38 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
39 from ansible.module_utils.api import retry_with_delays_and_condition
40 from ansible.module_utils.api import generate_jittered_backoff
41 from ansible.module_utils.common.process import get_bin_path
42 from ansible.module_utils.common.sentinel import Sentinel
43 from ansible.module_utils.common.yaml import yaml_load
44 from ansible.module_utils.urls import open_url
45 from ansible.utils.display import Display
46
47 import ansible.constants as C
48
49
50 display = Display()
51
52 MANIFEST_FILENAME = 'MANIFEST.json'
53
54
55 class ConcreteArtifactsManager:
56 """Manager for on-disk collection artifacts.
57
58 It is responsible for:
59 * downloading remote collections from Galaxy-compatible servers and
60 direct links to tarballs or SCM repositories
61 * keeping track of local ones
62 * keeping track of Galaxy API tokens for downloads from Galaxy'ish
63 as well as the artifact hashes
64 * keeping track of Galaxy API signatures for downloads from Galaxy'ish
65 * caching all of above
66 * retrieving the metadata out of the downloaded artifacts
67 """
68 def __init__(self, b_working_directory, validate_certs=True, keyring=None, timeout=60, required_signature_count=None, ignore_signature_errors=None):
69 # type: (bytes, bool, str, int, str, list[str]) -> None
70 """Initialize ConcreteArtifactsManager caches and constraints."""
71 self._validate_certs = validate_certs # type: bool
72 self._artifact_cache = {} # type: dict[bytes, bytes]
73 self._galaxy_artifact_cache = {} # type: dict[Candidate | Requirement, bytes]
74 self._artifact_meta_cache = {} # type: dict[bytes, dict[str, str | list[str] | dict[str, str] | None | t.Type[Sentinel]]]
75 self._galaxy_collection_cache: dict[Candidate, tuple[CollectionVersionMetadata, GalaxyAPI]] = {}
76 self._b_working_directory = b_working_directory # type: bytes
77 self._supplemental_signature_cache = {} # type: dict[str, str]
78 self._keyring = keyring # type: str
79 self.timeout = timeout # type: int
80 self._required_signature_count = required_signature_count # type: str
81 self._ignore_signature_errors = ignore_signature_errors # type: list[str]
82 self._require_build_metadata = True # type: bool
83
84 @property
85 def keyring(self):
86 return self._keyring
87
88 @property
89 def required_successful_signature_count(self):
90 return self._required_signature_count
91
92 @property
93 def ignore_signature_errors(self):
94 if self._ignore_signature_errors is None:
95 return []
96 return self._ignore_signature_errors
97
98 @property
99 def require_build_metadata(self):
100 # type: () -> bool
101 return self._require_build_metadata
102
103 @require_build_metadata.setter
104 def require_build_metadata(self, value):
105 # type: (bool) -> None
106 self._require_build_metadata = value
107
108 def get_galaxy_artifact_source_info(self, collection):
109 # type: (Candidate) -> dict[str, t.Union[str, list[dict[str, str]]]]
110
111 try:
112 metadata, server = self._galaxy_collection_cache[collection]
113 except KeyError as key_err:
114 raise RuntimeError(
115 f"There is no known source for {collection!s}"
116 ) from key_err
117
118 return {
119 "format_version": "1.0.0",
120 "namespace": collection.namespace,
121 "name": collection.name,
122 "version": collection.ver,
123 "server": server.api_server,
124 "version_url": metadata.signatures_url,
125 "download_url": metadata.download_url,
126 "signatures": metadata.signatures,
127 }
128
129 def get_galaxy_artifact_path(self, collection: Candidate) -> bytes:
130 """Given a Galaxy-stored collection, return a cached path.
131
132 If it's not yet on disk, this method downloads the artifact first.
133 """
134 try:
135 return self._galaxy_artifact_cache[collection]
136 except KeyError:
137 pass
138
139 try:
140 metadata, api = self._galaxy_collection_cache[collection]
141 except KeyError as key_err:
142 raise RuntimeError(
143 f'There is no known source for {collection!s}'
144 ) from key_err
145
146 display.vvvv(
147 "Fetching a collection tarball for '{collection!s}' from "
148 'Ansible Galaxy'.format(collection=collection),
149 )
150
151 try:
152 b_artifact_path = _download_file(
153 metadata.download_url,
154 self._b_working_directory,
155 expected_hash=metadata.artifact_sha256,
156 validate_certs=api.validate_certs,
157 token=api.token,
158 ) # type: bytes
159 except URLError as err:
160 raise AnsibleError(
161 'Failed to download collection tar '
162 f"from '{api!s}': {err!s}"
163 ) from err
164 except Exception as err:
165 raise AnsibleError(
166 'Failed to download collection tar '
167 f"from '{api!s}' due to the following unforeseen error: "
168 f'{err!s}'
169 ) from err
170 else:
171 display.vvv(
172 f"Collection '{collection!s}' obtained from server {api!s} "
173 f"{api.api_server!s}"
174 )
175
176 self._galaxy_artifact_cache[collection] = b_artifact_path
177 return b_artifact_path
178
179 def get_artifact_path(self, collection):
180 # type: (Collection) -> bytes
181 """Given a concrete collection pointer, return a cached path.
182
183 If it's not yet on disk, this method downloads the artifact first.
184 """
185 try:
186 return self._artifact_cache[collection.src]
187 except KeyError:
188 pass
189
190 # NOTE: SCM needs to be special-cased as it may contain either
191 # NOTE: one collection in its root, or a number of top-level
192 # NOTE: collection directories instead.
193 # NOTE: The idea is to store the SCM collection as unpacked
194 # NOTE: directory structure under the temporary location and use
195 # NOTE: a "virtual" collection that has pinned requirements on
196 # NOTE: the directories under that SCM checkout that correspond
197 # NOTE: to collections.
198 # NOTE: This brings us to the idea that we need two separate
199 # NOTE: virtual Requirement/Candidate types --
200 # NOTE: (single) dir + (multidir) subdirs
201 if collection.is_url:
202 display.vvvv(
203 "Collection requirement '{collection!s}' is a URL "
204 'to a tar artifact'.format(collection=collection.fqcn),
205 )
206 try:
207 b_artifact_path = _download_file(
208 collection.src,
209 self._b_working_directory,
210 expected_hash=None, # NOTE: URLs don't support checksums
211 validate_certs=self._validate_certs,
212 timeout=self.timeout
213 )
214 except Exception as err:
215 raise AnsibleError(
216 'Failed to download collection tar '
217 "from '{coll_src!s}': {download_err!s}".
218 format(
219 coll_src=to_native(collection.src),
220 download_err=to_native(err),
221 ),
222 ) from err
223 elif collection.is_scm:
224 b_artifact_path = _extract_collection_from_git(
225 collection.src,
226 collection.ver,
227 self._b_working_directory,
228 )
229 elif collection.is_file or collection.is_dir or collection.is_subdirs:
230 b_artifact_path = to_bytes(collection.src)
231 else:
232 # NOTE: This may happen `if collection.is_online_index_pointer`
233 raise RuntimeError(
234 'The artifact is of an unexpected type {art_type!s}'.
235 format(art_type=collection.type)
236 )
237
238 self._artifact_cache[collection.src] = b_artifact_path
239 return b_artifact_path
240
241 def get_artifact_path_from_unknown(self, collection):
242 # type: (Candidate) -> bytes
243 if collection.is_concrete_artifact:
244 return self.get_artifact_path(collection)
245 return self.get_galaxy_artifact_path(collection)
246
247 def _get_direct_collection_namespace(self, collection):
248 # type: (Candidate) -> t.Optional[str]
249 return self.get_direct_collection_meta(collection)['namespace'] # type: ignore[return-value]
250
251 def _get_direct_collection_name(self, collection):
252 # type: (Collection) -> t.Optional[str]
253 return self.get_direct_collection_meta(collection)['name'] # type: ignore[return-value]
254
255 def get_direct_collection_fqcn(self, collection):
256 # type: (Collection) -> t.Optional[str]
257 """Extract FQCN from the given on-disk collection artifact.
258
259 If the collection is virtual, ``None`` is returned instead
260 of a string.
261 """
262 if collection.is_virtual:
263 # NOTE: should it be something like "<virtual>"?
264 return None
265
266 return '.'.join(( # type: ignore[type-var]
267 self._get_direct_collection_namespace(collection), # type: ignore[arg-type]
268 self._get_direct_collection_name(collection),
269 ))
270
271 def get_direct_collection_version(self, collection):
272 # type: (Collection) -> str
273 """Extract version from the given on-disk collection artifact."""
274 return self.get_direct_collection_meta(collection)['version'] # type: ignore[return-value]
275
276 def get_direct_collection_dependencies(self, collection):
277 # type: (t.Union[Candidate, Requirement]) -> dict[str, str]
278 """Extract deps from the given on-disk collection artifact."""
279 collection_dependencies = self.get_direct_collection_meta(collection)['dependencies']
280 if collection_dependencies is None:
281 collection_dependencies = {}
282 return collection_dependencies # type: ignore[return-value]
283
284 def get_direct_collection_meta(self, collection):
285 # type: (Collection) -> dict[str, t.Union[str, dict[str, str], list[str], None, t.Type[Sentinel]]]
286 """Extract meta from the given on-disk collection artifact."""
287 try: # FIXME: use unique collection identifier as a cache key?
288 return self._artifact_meta_cache[collection.src]
289 except KeyError:
290 b_artifact_path = self.get_artifact_path(collection)
291
292 if collection.is_url or collection.is_file:
293 collection_meta = _get_meta_from_tar(b_artifact_path)
294 elif collection.is_dir: # should we just build a coll instead?
295 # FIXME: what if there's subdirs?
296 try:
297 collection_meta = _get_meta_from_dir(b_artifact_path, self.require_build_metadata)
298 except LookupError as lookup_err:
299 raise AnsibleError(
300 'Failed to find the collection dir deps: {err!s}'.
301 format(err=to_native(lookup_err)),
302 ) from lookup_err
303 elif collection.is_scm:
304 collection_meta = {
305 'name': None,
306 'namespace': None,
307 'dependencies': {to_native(b_artifact_path): '*'},
308 'version': '*',
309 }
310 elif collection.is_subdirs:
311 collection_meta = {
312 'name': None,
313 'namespace': None,
314 # NOTE: Dropping b_artifact_path since it's based on src anyway
315 'dependencies': dict.fromkeys(
316 map(to_native, collection.namespace_collection_paths),
317 '*',
318 ),
319 'version': '*',
320 }
321 else:
322 raise RuntimeError
323
324 self._artifact_meta_cache[collection.src] = collection_meta
325 return collection_meta
326
327 def get_direct_requires_ansible(self, collection: Candidate) -> str | None:
328 """Extract requires_ansible from the on-disk collection artifact."""
329 if collection.is_concrete_artifact:
330 b_artifact_path = self.get_artifact_path(collection)
331 else:
332 b_artifact_path = self.get_galaxy_artifact_path(collection)
333
334 if collection.is_url or collection.is_file or collection.is_online_index_pointer:
335 runtime = _get_runtime_from_tar(b_artifact_path) or {}
336 elif collection.is_dir:
337 runtime = _get_runtime_from_dir(b_artifact_path) or {}
338 elif collection.is_virtual:
339 runtime = {}
340
341 if not isinstance(runtime, Mapping):
342 raise AnsibleError(
343 f"The collection {collection} (type {collection.type}) (from {collection.src}) "
344 "has an invalid meta/runtime.yml metadata. This file must contain a YAML dictionary."
345 )
346 if "requires_ansible" in runtime and not isinstance(runtime["requires_ansible"], str):
347 raise AnsibleError(
348 f"The collection {collection} (type {collection.type}) from {collection.src}) "
349 "has invalid meta/runtime.yml metadata. The value for requires_ansible must be a string."
350 )
351 # NOTE: Using None as a sentinel since it's not a valid value otherwise.
352 return runtime.get("requires_ansible")
353
354 def save_collection_source(self, collection: Candidate, metadata: CollectionVersionMetadata, api: GalaxyAPI) -> None:
355 """Store collection version metadata and origin.
356
357 This is a hook that is supposed to be called before attempting to
358 download Galaxy-based collections with ``get_galaxy_artifact_path()``.
359 """
360 self._galaxy_collection_cache[collection] = (metadata, api)
361
362 @classmethod
363 @contextmanager
364 def under_tmpdir(
365 cls,
366 temp_dir_base, # type: str
367 validate_certs=True, # type: bool
368 keyring=None, # type: str
369 required_signature_count=None, # type: str
370 ignore_signature_errors=None, # type: list[str]
371 require_build_metadata=True, # type: bool
372 ): # type: (...) -> t.Iterator[ConcreteArtifactsManager]
373 """Custom ConcreteArtifactsManager constructor with temp dir.
374
375 This method returns a context manager that allocates and cleans
376 up a temporary directory for caching the collection artifacts
377 during the dependency resolution process.
378 """
379 # NOTE: Can't use `with tempfile.TemporaryDirectory:`
380 # NOTE: because it's not in Python 2 stdlib.
381 temp_path = mkdtemp(
382 dir=to_bytes(temp_dir_base, errors='surrogate_or_strict'),
383 )
384 b_temp_path = to_bytes(temp_path, errors='surrogate_or_strict')
385 try:
386 yield cls(
387 b_temp_path,
388 validate_certs,
389 keyring=keyring,
390 required_signature_count=required_signature_count,
391 ignore_signature_errors=ignore_signature_errors
392 )
393 finally:
394 rmtree(b_temp_path)
395
396
397 def parse_scm(collection, version):
398 """Extract name, version, path and subdir out of the SCM pointer."""
399 if ',' in collection:
400 collection, version = collection.split(',', 1)
401 elif version == '*' or not version:
402 version = 'HEAD'
403
404 if collection.startswith('git+'):
405 path = collection[4:]
406 else:
407 path = collection
408
409 path, fragment = urldefrag(path)
410 fragment = fragment.strip(os.path.sep)
411
412 if path.endswith(os.path.sep + '.git'):
413 name = path.split(os.path.sep)[-2]
414 elif '://' not in path and '@' not in path:
415 name = path
416 else:
417 name = path.split('/')[-1]
418 if name.endswith('.git'):
419 name = name[:-4]
420
421 return name, version, path, fragment
422
423
424 def _extract_collection_from_git(repo_url, coll_ver, b_path):
425 name, version, git_url, fragment = parse_scm(repo_url, coll_ver)
426 b_checkout_path = mkdtemp(
427 dir=b_path,
428 prefix=to_bytes(name, errors='surrogate_or_strict'),
429 )
430
431 try:
432 git_executable = get_bin_path('git')
433 except ValueError as err:
434 raise AnsibleError(
435 "Could not find git executable to extract the collection from the Git repository `{repo_url!s}`.".
436 format(repo_url=to_native(git_url))
437 ) from err
438
439 # Perform a shallow clone if simply cloning HEAD
440 if version == 'HEAD':
441 git_clone_cmd = [git_executable, 'clone', '--depth=1', git_url, to_text(b_checkout_path)]
442 else:
443 git_clone_cmd = [git_executable, 'clone', git_url, to_text(b_checkout_path)]
444 # FIXME: '--branch', version
445
446 if context.CLIARGS['ignore_certs'] or C.GALAXY_IGNORE_CERTS:
447 git_clone_cmd.extend(['-c', 'http.sslVerify=false'])
448
449 try:
450 subprocess.check_call(git_clone_cmd)
451 except subprocess.CalledProcessError as proc_err:
452 raise AnsibleError( # should probably be LookupError
453 'Failed to clone a Git repository from `{repo_url!s}`.'.
454 format(repo_url=to_native(git_url)),
455 ) from proc_err
456
457 if version == 'HEAD':
458 git_args = ()
459 else:
460 git_args = '-c', 'advice.detachedHead=false'
461
462 git_switch_cmd = git_executable, *git_args, 'checkout', to_text(version)
463 try:
464 subprocess.check_call(git_switch_cmd, cwd=b_checkout_path)
465 except subprocess.CalledProcessError as proc_err:
466 raise AnsibleError( # should probably be LookupError
467 'Failed to switch a cloned Git repo `{repo_url!s}` '
468 'to the requested revision `{revision!s}`.'.
469 format(
470 revision=to_native(version),
471 repo_url=to_native(git_url),
472 ),
473 ) from proc_err
474
475 return (
476 os.path.join(b_checkout_path, to_bytes(fragment))
477 if fragment else b_checkout_path
478 )
479
480
481 # FIXME: use random subdirs while preserving the file names
482 @retry_with_delays_and_condition(
483 backoff_iterator=generate_jittered_backoff(retries=6, delay_base=2, delay_threshold=40),
484 should_retry_error=should_retry_error
485 )
486 def _download_file(url, b_path, expected_hash, validate_certs, token=None, timeout=60):
487 # type: (str, bytes, t.Optional[str], bool, GalaxyToken, int) -> bytes
488 # ^ NOTE: used in download and verify_collections ^
489 b_tarball_name = to_bytes(
490 url.rsplit('/', 1)[1], errors='surrogate_or_strict',
491 )
492 b_file_name = b_tarball_name[:-len('.tar.gz')]
493
494 b_tarball_dir = mkdtemp(
495 dir=b_path,
496 prefix=b'-'.join((b_file_name, b'')),
497 ) # type: bytes
498
499 b_file_path = os.path.join(b_tarball_dir, b_tarball_name)
500
501 display.display("Downloading %s to %s" % (url, to_text(b_tarball_dir)))
502 # NOTE: Galaxy redirects downloads to S3 which rejects the request
503 # NOTE: if an Authorization header is attached so don't redirect it
504 resp = open_url(
505 to_native(url, errors='surrogate_or_strict'),
506 validate_certs=validate_certs,
507 headers=None if token is None else token.headers(),
508 unredirected_headers=['Authorization'], http_agent=user_agent(),
509 timeout=timeout
510 )
511
512 with open(b_file_path, 'wb') as download_file: # type: t.BinaryIO
513 try:
514 actual_hash = _consume_file(resp, write_to=download_file)
515 except IncompleteRead as orig_exc:
516 raise AnsibleError(f"Downloading {url} failed") from orig_exc
517
518 if expected_hash:
519 display.vvvv(
520 'Validating downloaded file hash {actual_hash!s} with '
521 'expected hash {expected_hash!s}'.
522 format(actual_hash=actual_hash, expected_hash=expected_hash)
523 )
524 if expected_hash != actual_hash:
525 raise AnsibleError('Mismatch artifact hash with downloaded file')
526
527 return b_file_path
528
529
530 def _consume_file(read_from: t.BinaryIO | HTTPResponse, write_to: t.BinaryIO | None = None) -> str:
531 bufsize = 65536
532 sha256_digest = sha256()
533 length = getattr(read_from, 'length', None)
534 actual_length = 0
535 remaining = None
536 while True:
537 if isinstance(length, int) and (remaining := length - actual_length) <= 0:
538 break
539
540 if not (data := read_from.read(min(bufsize, remaining or bufsize))):
541 break
542
543 if write_to is not None:
544 write_to.write(data)
545 write_to.flush()
546
547 sha256_digest.update(data)
548 actual_length += len(data)
549
550 if isinstance(length, int) and length > actual_length:
551 read_len = b' ' * actual_length if actual_length else b''
552 raise IncompleteRead(read_len, length - actual_length)
553
554 return sha256_digest.hexdigest()
555
556
557 def _normalize_galaxy_yml_manifest(
558 galaxy_yml, # type: dict[str, t.Union[str, list[str], dict[str, str], None, t.Type[Sentinel]]]
559 b_galaxy_yml_path, # type: bytes
560 require_build_metadata=True, # type: bool
561 ):
562 # type: (...) -> dict[str, t.Union[str, list[str], dict[str, str], None, t.Type[Sentinel]]]
563 galaxy_yml_schema = (
564 get_collections_galaxy_meta_info()
565 ) # type: list[dict[str, t.Any]] # FIXME: <--
566 # FIXME: 👆maybe precise type: list[dict[str, t.Union[bool, str, list[str]]]]
567
568 mandatory_keys = set()
569 string_keys = set() # type: set[str]
570 list_keys = set() # type: set[str]
571 dict_keys = set() # type: set[str]
572 sentinel_keys = set() # type: set[str]
573
574 for info in galaxy_yml_schema:
575 if info.get('required', False):
576 mandatory_keys.add(info['key'])
577
578 key_list_type = {
579 'str': string_keys,
580 'list': list_keys,
581 'dict': dict_keys,
582 'sentinel': sentinel_keys,
583 }[info.get('type', 'str')]
584 key_list_type.add(info['key'])
585
586 all_keys = frozenset(mandatory_keys | string_keys | list_keys | dict_keys | sentinel_keys)
587
588 set_keys = set(galaxy_yml.keys())
589 missing_keys = mandatory_keys.difference(set_keys)
590 if missing_keys:
591 msg = (
592 "The collection galaxy.yml at '%s' is missing the following mandatory keys: %s"
593 % (to_native(b_galaxy_yml_path), ", ".join(sorted(missing_keys)))
594 )
595 if require_build_metadata:
596 raise AnsibleError(msg)
597 display.warning(msg)
598 raise ValueError(msg)
599
600 extra_keys = set_keys.difference(all_keys)
601 if len(extra_keys) > 0:
602 display.warning("Found unknown keys in collection galaxy.yml at '%s': %s"
603 % (to_text(b_galaxy_yml_path), ", ".join(extra_keys)))
604
605 # Add the defaults if they have not been set
606 for optional_string in string_keys:
607 if optional_string not in galaxy_yml:
608 galaxy_yml[optional_string] = None
609
610 for optional_list in list_keys:
611 list_val = galaxy_yml.get(optional_list, None)
612
613 if list_val is None:
614 galaxy_yml[optional_list] = []
615 elif not isinstance(list_val, list):
616 galaxy_yml[optional_list] = [list_val] # type: ignore[list-item]
617
618 for optional_dict in dict_keys:
619 if optional_dict not in galaxy_yml:
620 galaxy_yml[optional_dict] = {}
621
622 for optional_sentinel in sentinel_keys:
623 if optional_sentinel not in galaxy_yml:
624 galaxy_yml[optional_sentinel] = Sentinel
625
626 # NOTE: `version: null` is only allowed for `galaxy.yml`
627 # NOTE: and not `MANIFEST.json`. The use-case for it is collections
628 # NOTE: that generate the version from Git before building a
629 # NOTE: distributable tarball artifact.
630 if not galaxy_yml.get('version'):
631 galaxy_yml['version'] = '*'
632
633 return galaxy_yml
634
635
636 def _get_meta_from_dir(
637 b_path, # type: bytes
638 require_build_metadata=True, # type: bool
639 ): # type: (...) -> dict[str, t.Union[str, list[str], dict[str, str], None, t.Type[Sentinel]]]
640 try:
641 return _get_meta_from_installed_dir(b_path)
642 except LookupError:
643 return _get_meta_from_src_dir(b_path, require_build_metadata)
644
645
646 def _get_meta_from_src_dir(
647 b_path, # type: bytes
648 require_build_metadata=True, # type: bool
649 ): # type: (...) -> dict[str, t.Union[str, list[str], dict[str, str], None, t.Type[Sentinel]]]
650 galaxy_yml = os.path.join(b_path, _GALAXY_YAML)
651 if not os.path.isfile(galaxy_yml):
652 raise LookupError(
653 "The collection galaxy.yml path '{path!s}' does not exist.".
654 format(path=to_native(galaxy_yml))
655 )
656
657 with open(galaxy_yml, 'rb') as manifest_file_obj:
658 try:
659 manifest = yaml_load(manifest_file_obj)
660 except yaml.error.YAMLError as yaml_err:
661 raise AnsibleError(
662 "Failed to parse the galaxy.yml at '{path!s}' with "
663 'the following error:\n{err_txt!s}'.
664 format(
665 path=to_native(galaxy_yml),
666 err_txt=to_native(yaml_err),
667 ),
668 ) from yaml_err
669
670 if not isinstance(manifest, dict):
671 if require_build_metadata:
672 raise AnsibleError(f"The collection galaxy.yml at '{to_native(galaxy_yml)}' is incorrectly formatted.")
673 # Valid build metadata is not required by ansible-galaxy list. Raise ValueError to fall back to implicit metadata.
674 display.warning(f"The collection galaxy.yml at '{to_native(galaxy_yml)}' is incorrectly formatted.")
675 raise ValueError(f"The collection galaxy.yml at '{to_native(galaxy_yml)}' is incorrectly formatted.")
676
677 return _normalize_galaxy_yml_manifest(manifest, galaxy_yml, require_build_metadata)
678
679
680 def _get_json_from_installed_dir(
681 b_path, # type: bytes
682 filename, # type: str
683 ): # type: (...) -> dict
684
685 b_json_filepath = os.path.join(b_path, to_bytes(filename, errors='surrogate_or_strict'))
686
687 try:
688 with open(b_json_filepath, 'rb') as manifest_fd:
689 b_json_text = manifest_fd.read()
690 except OSError as ex:
691 raise LookupError(f"The collection {filename!r} path {to_text(b_json_filepath)!r} does not exist.") from ex
692
693 manifest_txt = to_text(b_json_text, errors='surrogate_or_strict')
694
695 try:
696 manifest = json.loads(manifest_txt)
697 except ValueError:
698 raise AnsibleError(
699 'Collection tar file member {member!s} does not '
700 'contain a valid json string.'.
701 format(member=filename),
702 )
703
704 return manifest
705
706
707 def _get_meta_from_installed_dir(
708 b_path, # type: bytes
709 ): # type: (...) -> dict[str, t.Union[str, list[str], dict[str, str], None, t.Type[Sentinel]]]
710 manifest = _get_json_from_installed_dir(b_path, MANIFEST_FILENAME)
711 collection_info = manifest['collection_info']
712
713 version = collection_info.get('version')
714 if not version:
715 raise AnsibleError(
716 u'Collection metadata file `{manifest_filename!s}` at `{meta_file!s}` is expected '
717 u'to have a valid SemVer version value but got {version!s}'.
718 format(
719 manifest_filename=MANIFEST_FILENAME,
720 meta_file=to_text(b_path),
721 version=to_text(repr(version)),
722 ),
723 )
724
725 return collection_info
726
727
728 def _get_meta_from_tar(
729 b_path, # type: bytes
730 ): # type: (...) -> dict[str, t.Union[str, list[str], dict[str, str], None, t.Type[Sentinel]]]
731 if not os.path.exists(b_path):
732 raise AnsibleError(
733 f"Unable to find collection artifact file at '{to_native(b_path)}'."
734 )
735
736 if not tarfile.is_tarfile(b_path):
737 raise AnsibleError(
738 "Collection artifact at '{path!s}' is not a valid tar file.".
739 format(path=to_native(b_path)),
740 )
741
742 with tarfile.open(b_path, mode='r') as collection_tar: # type: tarfile.TarFile
743 try:
744 member = collection_tar.getmember(MANIFEST_FILENAME)
745 except KeyError:
746 raise AnsibleError(
747 "Collection at '{path!s}' does not contain the "
748 'required file {manifest_file!s}.'.
749 format(
750 path=to_native(b_path),
751 manifest_file=MANIFEST_FILENAME,
752 ),
753 )
754
755 with _tarfile_extract(collection_tar, member) as (_member, member_obj):
756 if member_obj is None:
757 raise AnsibleError(
758 'Collection tar file does not contain '
759 'member {member!s}'.format(member=MANIFEST_FILENAME),
760 )
761
762 text_content = to_text(
763 member_obj.read(),
764 errors='surrogate_or_strict',
765 )
766
767 try:
768 manifest = json.loads(text_content)
769 except ValueError:
770 raise AnsibleError(
771 'Collection tar file member {member!s} does not '
772 'contain a valid json string.'.
773 format(member=MANIFEST_FILENAME),
774 )
775 return manifest['collection_info']
776
777
778 @contextmanager
779 def _tarfile_extract(
780 tar, # type: tarfile.TarFile
781 member, # type: tarfile.TarInfo
782 ):
783 # type: (...) -> t.Iterator[tuple[tarfile.TarInfo, t.Optional[t.IO[bytes]]]]
784 tar_obj = tar.extractfile(member)
785 try:
786 yield member, tar_obj
787 finally:
788 if tar_obj is not None:
789 tar_obj.close()
790
791
792 @cache
793 def _get_runtime_from_dir(b_path: bytes) -> object:
794 """Load the meta/runtime.yml from a collection directory."""
795 runtime_path = Path(b_path.decode()) / "meta" / "runtime.yml"
796 with suppress(OSError):
797 return yaml_load(runtime_path.read_text())
798
799
800 @cache
801 def _get_runtime_from_tar(b_path: bytes) -> object:
802 """Load the meta/runtime.yml from a collection artifact."""
803 with suppress(tarfile.TarError, KeyError):
804 with tarfile.open(b_path, mode='r') as collection_tar:
805 runtime = collection_tar.getmember("meta/runtime.yml")
806 with _tarfile_extract(collection_tar, runtime) as (_member, member_obj):
807 return yaml_load(member_obj)