Debian Codegraph @

lib/ansible/galaxy/api.py

raw
1 # (C) 2013, James Cammarata <[email protected]>
2 # Copyright: (c) 2019, Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7 import collections
8 import datetime
9 import functools
10 import hashlib
11 import json
12 import os
13 import stat
14 import tarfile
15 import time
16 import threading
17
18 from http import HTTPStatus
19 from http.client import BadStatusLine, IncompleteRead
20 from urllib.error import HTTPError, URLError
21 from urllib.parse import quote as urlquote, urlencode, urlparse, parse_qs, urljoin
22
23 from ansible import constants as C
24 from ansible.errors import AnsibleError
25 from ansible.galaxy.user_agent import user_agent
26 from ansible.module_utils.api import retry_with_delays_and_condition
27 from ansible.module_utils.api import generate_jittered_backoff
28 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
29 from ansible.module_utils.urls import open_url, prepare_multipart
30 from ansible.utils.display import Display
31 from ansible.utils.hashing import secure_hash_s
32 from ansible.utils.path import makedirs_safe
33
34 display = Display()
35 _CACHE_LOCK = threading.Lock()
36 COLLECTION_PAGE_SIZE = 100
37 RETRY_HTTP_ERROR_CODES = { # TODO: Allow user-configuration
38 HTTPStatus.TOO_MANY_REQUESTS,
39 520, # Galaxy rate limit error code (Cloudflare unknown error)
40 HTTPStatus.BAD_GATEWAY, # Common error from galaxy that may represent any number of transient backend issues
41 }
42
43
44 def cache_lock(func):
45 def wrapped(*args, **kwargs):
46 with _CACHE_LOCK:
47 return func(*args, **kwargs)
48
49 return wrapped
50
51
52 def should_retry_error(exception):
53 # Note: cloud.redhat.com masks rate limit errors with 403 (Forbidden) error codes.
54 # Since 403 could reflect the actual problem (such as an expired token), we should
55 # not retry by default.
56 if isinstance(exception, GalaxyError) and exception.http_code in RETRY_HTTP_ERROR_CODES:
57 return True
58
59 if isinstance(exception, AnsibleError) and (cause := exception.__cause__):
60 # URLError is often a proxy for an underlying error, handle wrapped exceptions
61 if isinstance(cause, URLError):
62 cause = cause.reason
63
64 # Handle common URL related errors
65 if isinstance(cause, (TimeoutError, BadStatusLine, IncompleteRead)):
66 return True
67
68 return False
69
70
71 def g_connect(versions):
72 """
73 Wrapper to lazily initialize connection info to Galaxy and verify the API versions required are available on the
74 endpoint.
75
76 :param versions: A list of API versions that the function supports.
77 """
78 def decorator(method):
79 def wrapped(self, *args, **kwargs):
80 if not self._available_api_versions:
81 display.vvvv("Initial connection to galaxy_server: %s" % self.api_server)
82
83 # Determine the type of Galaxy server we are talking to. First try it unauthenticated then with Bearer
84 # auth for Automation Hub.
85 n_url = self.api_server
86 error_context_msg = 'Error when finding available api versions from %s (%s)' % (self.name, n_url)
87
88 if self.api_server == 'https://galaxy.ansible.com' or self.api_server == 'https://galaxy.ansible.com/':
89 n_url = 'https://galaxy.ansible.com/api/'
90
91 try:
92 data = self._call_galaxy(n_url, method='GET', error_context_msg=error_context_msg, cache=True)
93 except (AnsibleError, GalaxyError, ValueError, KeyError) as err:
94 # Either the URL doesn't exist, or other error. Or the URL exists, but isn't a galaxy API
95 # root (not JSON, no 'available_versions') so try appending '/api/'
96 if n_url.endswith('/api') or n_url.endswith('/api/'):
97 raise
98
99 # Let exceptions here bubble up but raise the original if this returns a 404 (/api/ wasn't found).
100 n_url = _urljoin(n_url, '/api/')
101 try:
102 data = self._call_galaxy(n_url, method='GET', error_context_msg=error_context_msg, cache=True)
103 except GalaxyError as new_err:
104 if new_err.http_code == 404:
105 raise err
106 raise
107
108 if 'available_versions' not in data:
109 raise AnsibleError("Tried to find galaxy API root at %s but no 'available_versions' are available "
110 "on %s" % (n_url, self.api_server))
111
112 # Update api_server to point to the "real" API root, which in this case could have been the configured
113 # url + '/api/' appended.
114 self.api_server = n_url
115
116 self._available_api_versions = available_versions = data['available_versions']
117 display.vvvv("Found API version '%s' with Galaxy server %s (%s)"
118 % (', '.join(available_versions.keys()), self.name, self.api_server))
119
120 # Verify that the API versions the function works with are available on the server specified.
121 available_versions = set(self._available_api_versions.keys())
122 common_versions = set(versions).intersection(available_versions)
123 if not common_versions:
124 raise AnsibleError("Galaxy action %s requires API versions '%s' but only '%s' are available on %s %s"
125 % (method.__name__, ", ".join(versions), ", ".join(available_versions),
126 self.name, self.api_server))
127
128 return method(self, *args, **kwargs)
129 return wrapped
130 return decorator
131
132
133 def get_cache_id(url):
134 """ Gets the cache ID for the URL specified. """
135 url_info = urlparse(url)
136
137 port = None
138 try:
139 port = url_info.port
140 except ValueError:
141 pass # While the URL is probably invalid, let the caller figure that out when using it
142
143 # Cannot use netloc because it could contain credentials if the server specified had them in there.
144 return '%s:%s' % (url_info.hostname, port or '')
145
146
147 @cache_lock
148 def _load_cache(b_cache_path):
149 """ Loads the cache file requested if possible. The file must not be world writable. """
150 cache_version = 1
151
152 if not os.path.isfile(b_cache_path):
153 display.vvvv("Creating Galaxy API response cache file at '%s'" % to_text(b_cache_path))
154 with open(b_cache_path, 'w'):
155 os.chmod(b_cache_path, 0o600)
156
157 cache_mode = os.stat(b_cache_path).st_mode
158 if cache_mode & stat.S_IWOTH:
159 display.warning("Galaxy cache has world writable access (%s), ignoring it as a cache source."
160 % to_text(b_cache_path))
161 return
162
163 with open(b_cache_path, mode='rb') as fd:
164 json_val = to_text(fd.read(), errors='surrogate_or_strict')
165
166 try:
167 cache = json.loads(json_val)
168 except ValueError:
169 cache = None
170
171 if not isinstance(cache, dict) or cache.get('version', None) != cache_version:
172 display.vvvv("Galaxy cache file at '%s' has an invalid version, clearing" % to_text(b_cache_path))
173 cache = {'version': cache_version}
174
175 # Set the cache after we've cleared the existing entries
176 with open(b_cache_path, mode='wb') as fd:
177 fd.write(to_bytes(json.dumps(cache), errors='surrogate_or_strict'))
178
179 return cache
180
181
182 def _urljoin(*args):
183 return '/'.join(to_native(a, errors='surrogate_or_strict').strip('/') for a in args + ('',) if a)
184
185
186 class GalaxyError(AnsibleError):
187 """ Error for bad Galaxy server responses. """
188
189 def __init__(self, http_error, message):
190 super(GalaxyError, self).__init__(message)
191 self.http_code = http_error.code
192 self.url = http_error.geturl()
193
194 try:
195 http_msg = to_text(http_error.read())
196 err_info = json.loads(http_msg)
197 except (AttributeError, ValueError):
198 err_info = {}
199
200 url_split = self.url.split('/')
201 if 'v3' in url_split:
202 errors = err_info.get('errors', [])
203 if not errors:
204 errors = [{}] # Defaults are set below, we just need to make sure 1 error is present.
205
206 message_lines = []
207 for error in errors:
208 error_msg = error.get('detail') or error.get('title') or http_error.reason
209 error_code = error.get('code') or 'Unknown'
210 message_line = u"(HTTP Code: %d, Message: %s Code: %s)" % (self.http_code, error_msg, error_code)
211 message_lines.append(message_line)
212
213 full_error_msg = "%s %s" % (message, ', '.join(message_lines))
214 else:
215 # v1 and unknown API endpoints
216 galaxy_msg = err_info.get('default', http_error.reason)
217 full_error_msg = u"%s (HTTP Code: %d, Message: %s)" % (message, self.http_code, galaxy_msg)
218
219 self.message = to_native(full_error_msg)
220
221
222 # Keep the raw string results for the date. It's too complex to parse as a datetime object and the various APIs return
223 # them in different formats.
224 CollectionMetadata = collections.namedtuple('CollectionMetadata', ['namespace', 'name', 'created_str', 'modified_str'])
225
226
227 class CollectionVersionMetadata:
228
229 def __init__(self, namespace, name, version, download_url, artifact_sha256, dependencies, signatures_url, signatures):
230 """
231 Contains common information about a collection on a Galaxy server to smooth through API differences for
232 Collection and define a standard meta info for a collection.
233
234 :param namespace: The namespace name.
235 :param name: The collection name.
236 :param version: The version that the metadata refers to.
237 :param download_url: The URL to download the collection.
238 :param artifact_sha256: The SHA256 of the collection artifact for later verification.
239 :param dependencies: A dict of dependencies of the collection.
240 :param signatures_url: The URL to the specific version of the collection.
241 :param signatures: The list of signatures found at the signatures_url.
242 """
243 self.namespace = namespace
244 self.name = name
245 self.version = version
246 self.download_url = download_url
247 self.artifact_sha256 = artifact_sha256
248 self.dependencies = dependencies
249 self.signatures_url = signatures_url
250 self.signatures = signatures
251
252
253 @functools.total_ordering
254 class GalaxyAPI:
255 """ This class is meant to be used as a API client for an Ansible Galaxy server """
256
257 def __init__(
258 self, galaxy, name, url,
259 username=None, password=None, token=None, validate_certs=True,
260 available_api_versions=None,
261 clear_response_cache=False, no_cache=True,
262 priority=float('inf'),
263 timeout=60,
264 ):
265 self.galaxy = galaxy
266 self.name = name
267 self.username = username
268 self.password = password
269 self.token = token
270 self.api_server = url
271 self.validate_certs = validate_certs
272 self.timeout = timeout
273 self._available_api_versions = available_api_versions or {}
274 self._priority = priority
275 self._server_timeout = timeout
276
277 b_cache_dir = to_bytes(C.GALAXY_CACHE_DIR, errors='surrogate_or_strict')
278 makedirs_safe(b_cache_dir, mode=0o700)
279 self._b_cache_path = os.path.join(b_cache_dir, b'api.json')
280
281 if clear_response_cache:
282 with _CACHE_LOCK:
283 if os.path.exists(self._b_cache_path):
284 display.vvvv("Clearing cache file (%s)" % to_text(self._b_cache_path))
285 os.remove(self._b_cache_path)
286
287 self._cache = None
288 if not no_cache:
289 self._cache = _load_cache(self._b_cache_path)
290
291 self.requires_ansible = collections.defaultdict(dict)
292
293 display.debug('Validate TLS certificates for %s: %s' % (self.api_server, self.validate_certs))
294
295 def __str__(self):
296 # type: (GalaxyAPI) -> str
297 """Render GalaxyAPI as a native string representation."""
298 return to_native(self.name)
299
300 def __unicode__(self):
301 # type: (GalaxyAPI) -> str
302 """Render GalaxyAPI as a unicode/text string representation."""
303 return to_text(self.name)
304
305 def __repr__(self):
306 # type: (GalaxyAPI) -> str
307 """Render GalaxyAPI as an inspectable string representation."""
308 return (
309 '<{instance!s} "{name!s}" @ {url!s} with priority {priority!s}>'.
310 format(
311 instance=self, name=self.name,
312 priority=self._priority, url=self.api_server,
313 )
314 )
315
316 def __lt__(self, other_galaxy_api):
317 # type: (GalaxyAPI, GalaxyAPI) -> bool
318 """Return whether the instance priority is higher than other."""
319 if not isinstance(other_galaxy_api, self.__class__):
320 return NotImplemented
321
322 return self._priority > other_galaxy_api._priority
323
324 @property # type: ignore[misc] # https://github.com/python/mypy/issues/1362
325 @g_connect(['v1', 'v3'])
326 def available_api_versions(self):
327 # Calling g_connect will populate self._available_api_versions
328 return self._available_api_versions
329
330 @retry_with_delays_and_condition(
331 backoff_iterator=generate_jittered_backoff(retries=6, delay_base=2, delay_threshold=40),
332 should_retry_error=should_retry_error
333 )
334 def _call_galaxy(self, url, args=None, headers=None, method=None, auth_required=False, error_context_msg=None,
335 cache=False, cache_key=None):
336 url_info = urlparse(url)
337 cache_id = get_cache_id(url)
338 if not cache_key:
339 cache_key = url_info.path
340 query = parse_qs(url_info.query)
341 if cache and self._cache:
342 server_cache = self._cache.setdefault(cache_id, {})
343 iso_datetime_format = '%Y-%m-%dT%H:%M:%SZ'
344
345 valid = False
346 if cache_key in server_cache:
347 expires = datetime.datetime.strptime(server_cache[cache_key]['expires'], iso_datetime_format)
348 expires = expires.replace(tzinfo=datetime.timezone.utc)
349 valid = datetime.datetime.now(datetime.timezone.utc) < expires
350
351 is_paginated_url = 'page' in query or 'offset' in query
352 if valid and not is_paginated_url:
353 # Got a hit on the cache and we aren't getting a paginated response
354 path_cache = server_cache[cache_key]
355 if path_cache.get('paginated'):
356 if '/v3/' in cache_key:
357 res = {'links': {'next': None}}
358 else:
359 res = {'next': None}
360
361 # Technically some v3 paginated APIs return in 'data' but the caller checks the keys for this so
362 # always returning the cache under results is fine.
363 res['results'] = []
364 for result in path_cache['results']:
365 res['results'].append(result)
366
367 else:
368 try:
369 res = path_cache['results']
370 except KeyError as cache_miss_error:
371 raise AnsibleError(
372 f"Missing expected 'results' in ansible-galaxy cache: {path_cache!r}. "
373 "This may indicate cache corruption (for example, from concurrent ansible-galaxy runs) "
374 "or a bug in how the cache was generated. "
375 "Try running with --clear-response-cache or --no-cache to work around the issue."
376 ) from cache_miss_error
377
378 return res
379
380 elif not is_paginated_url:
381 # The cache entry had expired or does not exist, start a new blank entry to be filled later.
382 expires = datetime.datetime.now(datetime.timezone.utc)
383 expires += datetime.timedelta(days=1)
384 server_cache[cache_key] = {
385 'expires': expires.strftime(iso_datetime_format),
386 'paginated': False,
387 }
388
389 headers = headers or {}
390 self._add_auth_token(headers, url, required=auth_required)
391
392 try:
393 display.vvvv("Calling Galaxy at %s" % url)
394 resp = open_url(to_native(url), data=args, validate_certs=self.validate_certs, headers=headers,
395 method=method, timeout=self._server_timeout, http_agent=user_agent(), follow_redirects='safe')
396 except HTTPError as e:
397 raise GalaxyError(e, error_context_msg)
398 except Exception as ex:
399 raise AnsibleError(f"Unknown error when attempting to call Galaxy at {url!r}.") from ex
400
401 resp_data = to_text(resp.read(), errors='surrogate_or_strict')
402 try:
403 data = json.loads(resp_data)
404 except ValueError:
405 raise AnsibleError("Failed to parse Galaxy response from '%s' as JSON:\n%s"
406 % (resp.url, to_native(resp_data)))
407
408 if cache and self._cache:
409 path_cache = self._cache[cache_id][cache_key]
410
411 # v3 can return data or results for paginated results. Scan the result so we can determine what to cache.
412 paginated_key = None
413 for key in ['data', 'results']:
414 if key in data:
415 paginated_key = key
416 break
417
418 if paginated_key:
419 path_cache['paginated'] = True
420 results = path_cache.setdefault('results', [])
421 for result in data[paginated_key]:
422 results.append(result)
423
424 else:
425 path_cache['results'] = data
426
427 return data
428
429 def _add_auth_token(self, headers, url, token_type=None, required=False):
430 # Don't add the auth token if one is already present
431 if 'Authorization' in headers:
432 return
433
434 if not self.token and required:
435 raise AnsibleError("No access token or username set. A token can be set with --api-key "
436 "or at {0}.".format(to_native(C.GALAXY_TOKEN_PATH)))
437
438 if self.token:
439 headers.update(self.token.headers())
440
441 @cache_lock
442 def _set_cache(self):
443 with open(self._b_cache_path, mode='wb') as fd:
444 fd.write(to_bytes(json.dumps(self._cache), errors='surrogate_or_strict'))
445
446 @g_connect(['v1'])
447 def authenticate(self, github_token):
448 """
449 Retrieve an authentication token
450 """
451 url = _urljoin(self.api_server, self.available_api_versions['v1'], "tokens") + '/'
452 args = urlencode({"github_token": github_token})
453
454 try:
455 resp = open_url(url, data=args, validate_certs=self.validate_certs, method="POST", http_agent=user_agent(), timeout=self._server_timeout)
456 except HTTPError as e:
457 raise GalaxyError(e, 'Attempting to authenticate to galaxy')
458 except Exception as ex:
459 raise AnsibleError('Unable to authenticate to galaxy.') from ex
460
461 data = json.loads(to_text(resp.read(), errors='surrogate_or_strict'))
462 return data
463
464 @g_connect(['v1'])
465 def create_import_task(self, github_user, github_repo, reference=None, role_name=None):
466 """
467 Post an import request
468 """
469 url = _urljoin(self.api_server, self.available_api_versions['v1'], "imports") + '/'
470 args = {
471 "github_user": github_user,
472 "github_repo": github_repo,
473 "github_reference": reference if reference else ""
474 }
475 if role_name:
476 args['alternate_role_name'] = role_name
477 data = self._call_galaxy(url, args=urlencode(args), method="POST")
478 if data.get('results', None):
479 return data['results']
480 return data
481
482 @g_connect(['v1'])
483 def get_import_task(self, task_id=None, github_user=None, github_repo=None):
484 """
485 Check the status of an import task.
486 """
487 url = _urljoin(self.api_server, self.available_api_versions['v1'], "imports")
488 if task_id is not None:
489 url = "%s?id=%d" % (url, task_id)
490 elif github_user is not None and github_repo is not None:
491 url = "%s?github_user=%s&github_repo=%s" % (url, github_user, github_repo)
492 else:
493 raise AnsibleError("Expected task_id or github_user and github_repo")
494
495 data = self._call_galaxy(url)
496 return data['results']
497
498 @g_connect(['v1'])
499 def lookup_role_by_name(self, role_name, notify=True):
500 """
501 Find a role by name.
502 """
503 role_name = to_text(urlquote(to_bytes(role_name)))
504
505 try:
506 parts = role_name.split(".")
507 user_name = ".".join(parts[0:-1])
508 role_name = parts[-1]
509 if notify:
510 display.display("- downloading role '%s', owned by %s" % (role_name, user_name))
511 except Exception:
512 raise AnsibleError("Invalid role name (%s). Specify role as format: username.rolename" % role_name)
513
514 url = _urljoin(self.api_server, self.available_api_versions['v1'], "roles",
515 "?owner__username=%s&name=%s" % (user_name, role_name))
516 data = self._call_galaxy(url)
517 if len(data["results"]) != 0:
518 return data["results"][0]
519 return None
520
521 @g_connect(['v1'])
522 def fetch_role_related(self, related, role_id):
523 """
524 Fetch the list of related items for the given role.
525 The url comes from the 'related' field of the role.
526 """
527
528 results = []
529 try:
530 url = _urljoin(self.api_server, self.available_api_versions['v1'], "roles", role_id, related,
531 "?page_size=50")
532 data = self._call_galaxy(url)
533 results = data['results']
534 done = (data.get('next_link', None) is None)
535
536 # https://github.com/ansible/ansible/issues/64355
537 # api_server contains part of the API path but next_link includes the /api part so strip it out.
538 url_info = urlparse(self.api_server)
539 base_url = "%s://%s/" % (url_info.scheme, url_info.netloc)
540
541 while not done:
542 url = _urljoin(base_url, data['next_link'])
543 data = self._call_galaxy(url)
544 results += data['results']
545 done = (data.get('next_link', None) is None)
546 except Exception as e:
547 display.warning("Unable to retrieve role (id=%s) data (%s), but this is not fatal so we continue: %s"
548 % (role_id, related, to_text(e)))
549 return results
550
551 @g_connect(['v1'])
552 def get_list(self, what):
553 """
554 Fetch the list of items specified.
555 """
556 try:
557 url = _urljoin(self.api_server, self.available_api_versions['v1'], what, "?page_size")
558 data = self._call_galaxy(url)
559 if "results" in data:
560 results = data['results']
561 else:
562 results = data
563 done = True
564 if "next" in data:
565 done = (data.get('next_link', None) is None)
566 while not done:
567 url = _urljoin(self.api_server, data['next_link'])
568 data = self._call_galaxy(url)
569 results += data['results']
570 done = (data.get('next_link', None) is None)
571 return results
572 except Exception as error:
573 raise AnsibleError("Failed to download the %s list: %s" % (what, to_native(error)))
574
575 @g_connect(['v1'])
576 def search_roles(self, search, **kwargs):
577
578 search_url = _urljoin(self.api_server, self.available_api_versions['v1'], "search", "roles", "?")
579
580 if search:
581 search_url += '&autocomplete=' + to_text(urlquote(to_bytes(search)))
582
583 tags = kwargs.get('tags', None)
584 platforms = kwargs.get('platforms', None)
585 page_size = kwargs.get('page_size', None)
586 author = kwargs.get('author', None)
587
588 if tags and isinstance(tags, str):
589 tags = tags.split(',')
590 search_url += '&tags_autocomplete=' + '+'.join(tags)
591
592 if platforms and isinstance(platforms, str):
593 platforms = platforms.split(',')
594 search_url += '&platforms_autocomplete=' + '+'.join(platforms)
595
596 if page_size:
597 search_url += '&page_size=%s' % page_size
598
599 if author:
600 search_url += '&username_autocomplete=%s' % author
601
602 data = self._call_galaxy(search_url)
603 return data
604
605 @g_connect(['v1'])
606 def add_secret(self, source, github_user, github_repo, secret):
607 url = _urljoin(self.api_server, self.available_api_versions['v1'], "notification_secrets") + '/'
608 args = urlencode({
609 "source": source,
610 "github_user": github_user,
611 "github_repo": github_repo,
612 "secret": secret
613 })
614 data = self._call_galaxy(url, args=args, method="POST")
615 return data
616
617 @g_connect(['v1'])
618 def list_secrets(self):
619 url = _urljoin(self.api_server, self.available_api_versions['v1'], "notification_secrets")
620 data = self._call_galaxy(url, auth_required=True)
621 return data
622
623 @g_connect(['v1'])
624 def remove_secret(self, secret_id):
625 url = _urljoin(self.api_server, self.available_api_versions['v1'], "notification_secrets", secret_id) + '/'
626 data = self._call_galaxy(url, auth_required=True, method='DELETE')
627 return data
628
629 @g_connect(['v1'])
630 def delete_role(self, github_user, github_repo):
631 url = _urljoin(self.api_server, self.available_api_versions['v1'], "removerole",
632 "?github_user=%s&github_repo=%s" % (github_user, github_repo))
633 data = self._call_galaxy(url, auth_required=True, method='DELETE')
634 return data
635
636 # Collection APIs #
637
638 @g_connect(['v3'])
639 def publish_collection(self, collection_path):
640 """
641 Publishes a collection to a Galaxy server and returns the import task URI.
642
643 :param collection_path: The path to the collection tarball to publish.
644 :return: The import task URI that contains the import results.
645 """
646 display.display("Publishing collection artifact '%s' to %s %s" % (collection_path, self.name, self.api_server))
647
648 b_collection_path = to_bytes(collection_path, errors='surrogate_or_strict')
649 if not os.path.exists(b_collection_path):
650 raise AnsibleError("The collection path specified '%s' does not exist." % to_native(collection_path))
651 elif not tarfile.is_tarfile(b_collection_path):
652 raise AnsibleError("The collection path specified '%s' is not a tarball, use 'ansible-galaxy collection "
653 "build' to create a proper release artifact." % to_native(collection_path))
654
655 with open(b_collection_path, 'rb') as collection_tar:
656 sha256 = secure_hash_s(collection_tar.read(), hash_func=hashlib.sha256)
657
658 content_type, b_form_data = prepare_multipart(
659 {
660 'sha256': sha256,
661 'file': {
662 'filename': b_collection_path,
663 'mime_type': 'application/octet-stream',
664 },
665 }
666 )
667
668 headers = {
669 'Content-type': content_type,
670 'Content-length': len(b_form_data),
671 }
672
673 n_url = _urljoin(self.api_server, self.available_api_versions['v3'], 'artifacts', 'collections') + '/'
674 resp = self._call_galaxy(n_url, args=b_form_data, headers=headers, method='POST', auth_required=True,
675 error_context_msg='Error when publishing collection to %s (%s)'
676 % (self.name, self.api_server))
677
678 return urljoin(self.api_server, resp['task'])
679
680 @g_connect(['v3'])
681 def wait_import_task(self, task_url, timeout=0):
682 """
683 Waits until the import process on the Galaxy server has completed or the timeout is reached.
684
685 :param task_id: The id of the import task to wait for. This can be parsed out of the return
686 value for GalaxyAPI.publish_collection.
687 :param timeout: The timeout in seconds, 0 is no timeout.
688 """
689 state = 'waiting'
690 data = None
691
692 display.display("Waiting until Galaxy import task %s has completed" % task_url)
693 start = time.time()
694 wait = C.GALAXY_COLLECTION_IMPORT_POLL_INTERVAL
695
696 while timeout == 0 or (time.time() - start) < timeout:
697 try:
698 data = self._call_galaxy(task_url, method='GET', auth_required=True,
699 error_context_msg='Error when getting import task results at %s' % task_url)
700 except GalaxyError as e:
701 if e.http_code != 404:
702 raise
703 # The import job may not have started, and as such, the task url may not yet exist
704 display.vvv('Galaxy import process has not started, wait %s seconds before trying again' % wait)
705 time.sleep(wait)
706 continue
707
708 state = data.get('state', 'waiting')
709
710 if data.get('finished_at', None):
711 break
712
713 display.vvv('Galaxy import process has a status of %s, wait %d seconds before trying again'
714 % (state, wait))
715 time.sleep(wait)
716
717 # poor man's exponential backoff algo so we don't flood the Galaxy API, cap at 30 seconds.
718 wait = min(30, wait * C.GALAXY_COLLECTION_IMPORT_POLL_FACTOR)
719 if state == 'waiting':
720 raise AnsibleError("Timeout while waiting for the Galaxy import process to finish, check progress at '%s'"
721 % to_native(task_url))
722
723 for message in data.get('messages', []):
724 level = message['level']
725 if level.lower() == 'error':
726 display.error("Galaxy import error message: %s" % message['message'])
727 elif level.lower() == 'warning':
728 display.warning("Galaxy import warning message: %s" % message['message'])
729 else:
730 display.vvv("Galaxy import message: %s - %s" % (level, message['message']))
731
732 if state == 'failed':
733 code = to_native(data['error'].get('code', 'UNKNOWN'))
734 description = to_native(
735 data['error'].get('description', "Unknown error, see %s for more details" % task_url))
736 raise AnsibleError("Galaxy import process failed: %s (Code: %s)" % (description, code))
737
738 @g_connect(['v3'])
739 def get_collection_metadata(self, namespace, name):
740 """
741 Gets the collection information from the Galaxy server about a specific Collection.
742
743 :param namespace: The collection namespace.
744 :param name: The collection name.
745 return: CollectionMetadata about the collection.
746 """
747 api_path = self.available_api_versions['v3']
748 field_map = [
749 ('created_str', 'created_at'),
750 ('modified_str', 'updated_at'),
751 ]
752
753 info_url = _urljoin(self.api_server, api_path, 'collections', namespace, name, '/')
754 error_context_msg = 'Error when getting the collection info for %s.%s from %s (%s)' \
755 % (namespace, name, self.name, self.api_server)
756 data = self._call_galaxy(info_url, error_context_msg=error_context_msg)
757
758 metadata = {}
759 for name, api_field in field_map:
760 metadata[name] = data.get(api_field, None)
761
762 return CollectionMetadata(namespace, name, **metadata)
763
764 @g_connect(['v3'])
765 def get_collection_version_metadata(self, namespace, name, version):
766 """
767 Gets the collection information from the Galaxy server about a specific Collection version.
768
769 :param namespace: The collection namespace.
770 :param name: The collection name.
771 :param version: Version of the collection to get the information for.
772 :return: CollectionVersionMetadata about the collection at the version requested.
773 """
774 api_path = self.available_api_versions['v3']
775 url_paths = [self.api_server, api_path, 'collections', namespace, name, 'versions', version, '/']
776
777 n_collection_url = _urljoin(*url_paths)
778 error_context_msg = 'Error when getting collection version metadata for %s.%s:%s from %s (%s)' \
779 % (namespace, name, version, self.name, self.api_server)
780 data = self._call_galaxy(n_collection_url, error_context_msg=error_context_msg, cache=True)
781 self._set_cache()
782
783 signatures = data.get('signatures') or []
784
785 # NOTE: Galaxy and Hub already populated the cache when listing versions.
786 # NOTE: Allow 3rd party servers to provide version-specific metadata lazily.
787 if (requires_ansible := data.get('requires_ansible')):
788 self.requires_ansible[f"{namespace}.{name}"][version] = requires_ansible
789
790 download_url_info = urlparse(data['download_url'])
791 if not download_url_info.scheme and not download_url_info.path.startswith('/'):
792 # galaxy does a lot of redirects, with much more complex pathing than we use
793 # within this codebase, without updating _call_galaxy to be able to return
794 # the final URL, we can't reliably build a relative URL.
795 raise AnsibleError(f'Invalid non absolute download_url: {data["download_url"]}')
796
797 download_url = urljoin(self.api_server, data['download_url'])
798
799 return CollectionVersionMetadata(data['namespace']['name'], data['collection']['name'], data['version'],
800 download_url, data['artifact']['sha256'],
801 data['metadata']['dependencies'], data['href'], signatures)
802
803 @g_connect(['v3'])
804 def get_collection_versions(self, namespace, name):
805 """
806 Gets a list of available versions for a collection on a Galaxy server.
807
808 :param namespace: The collection namespace.
809 :param name: The collection name.
810 :return: A list of versions that are available.
811 """
812 api_path = self.available_api_versions['v3']
813 pagination_path = ['links', 'next']
814
815 versions_url = _urljoin(self.api_server, api_path, 'collections', namespace, name, 'versions', '/?limit=%d' % COLLECTION_PAGE_SIZE)
816 versions_url_info = urlparse(versions_url)
817 cache_key = versions_url_info.path
818
819 # We should only rely on the cache if the collection has not changed. This may slow things down but it ensures
820 # we are not waiting a day before finding any new collections that have been published.
821 if self._cache:
822 server_cache = self._cache.setdefault(get_cache_id(versions_url), {})
823 modified_cache = server_cache.setdefault('modified', {})
824
825 try:
826 modified_date = self.get_collection_metadata(namespace, name).modified_str
827 except GalaxyError as err:
828 if err.http_code != 404:
829 raise
830 # No collection found, return an empty list to keep things consistent with the various APIs
831 return []
832
833 cached_modified_date = modified_cache.get('%s.%s' % (namespace, name), None)
834 if cached_modified_date != modified_date:
835 modified_cache['%s.%s' % (namespace, name)] = modified_date
836 if versions_url_info.path in server_cache:
837 del server_cache[cache_key]
838
839 self._set_cache()
840
841 error_context_msg = 'Error when getting available collection versions for %s.%s from %s (%s)' \
842 % (namespace, name, self.name, self.api_server)
843
844 try:
845 data = self._call_galaxy(versions_url, error_context_msg=error_context_msg, cache=True, cache_key=cache_key)
846 except GalaxyError as err:
847 if err.http_code != 404:
848 raise
849 # v3 doesn't raise a 404 so we need to mimic the empty response from APIs that do.
850 return []
851
852 if 'data' in data:
853 # v3 automation-hub is the only known API that uses `data`
854 # since v3 pulp_ansible does not, we cannot rely on version
855 # to indicate which key to use
856 results_key = 'data'
857 else:
858 results_key = 'results'
859
860 versions = []
861 while True:
862 for v in data[results_key]:
863 versions.append(v["version"])
864 # requires_ansible is new in galaxy_ng 4.3.0
865 self.requires_ansible[f"{namespace}.{name}"][v["version"]] = v.get("requires_ansible")
866
867 next_link = data
868 for path in pagination_path:
869 next_link = next_link.get(path, {})
870
871 if not next_link:
872 break
873 next_link_info = urlparse(next_link)
874 if not next_link_info.scheme and not next_link_info.path.startswith('/'):
875 raise AnsibleError(f'Invalid non absolute pagination link: {next_link}')
876 next_link = urljoin(self.api_server, next_link)
877
878 data = self._call_galaxy(to_native(next_link, errors='surrogate_or_strict'),
879 error_context_msg=error_context_msg, cache=True, cache_key=cache_key)
880 self._set_cache()
881
882 return versions
883
884 @g_connect(['v3'])
885 def get_collection_signatures(self, namespace, name, version):
886 """
887 Gets the collection signatures from the Galaxy server about a specific Collection version.
888
889 :param namespace: The collection namespace.
890 :param name: The collection name.
891 :param version: Version of the collection to get the information for.
892 :return: A list of signature strings.
893 """
894 api_path = self.available_api_versions['v3']
895 url_paths = [self.api_server, api_path, 'collections', namespace, name, 'versions', version, '/']
896
897 n_collection_url = _urljoin(*url_paths)
898 error_context_msg = 'Error when getting collection version metadata for %s.%s:%s from %s (%s)' \
899 % (namespace, name, version, self.name, self.api_server)
900 data = self._call_galaxy(n_collection_url, error_context_msg=error_context_msg, cache=True)
901 self._set_cache()
902
903 signatures = [signature_info["signature"] for signature_info in data.get("signatures") or []]
904 if not signatures:
905 display.vvvv(f"Server {self.api_server} has not signed {namespace}.{name}:{version}")
906 return signatures