Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/scripts/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,9 @@ fi
# Needed for some functional tests
cmd_prefix bash -c "echo '%wheel ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/nopasswd"
cmd_prefix bash -c "usermod -a -G wheel pulp"

# In some scenarios we want to simulate a failed redis cache.
if [[ " s3 " =~ " ${TEST} " ]]; then
cmd_prefix bash -c "s6-rc -d change redis"
echo "The Redis service was disabled for $TEST"
fi
1 change: 1 addition & 0 deletions CHANGES/1428.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed pip intermittently receiving a pull-through wheel instead of its metadata, or the reverse, when Redis caching is enabled.
43 changes: 30 additions & 13 deletions pulp_python/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from django.db import models, transaction
from django_lifecycle import (
AFTER_UPDATE,
BEFORE_DELETE,
BEFORE_SAVE,
hook,
)
Expand Down Expand Up @@ -41,6 +42,8 @@
artifact_to_metadata_artifact,
artifact_to_python_content_data,
canonicalize_name,
clear_pull_through_entries,
lookup_pull_through_entry,
python_content_to_json,
unsign_pull_through_token,
)
Expand Down Expand Up @@ -360,19 +363,21 @@ class PythonRemote(Remote, AutoAddObjPermsMixin):
vulnerabilities = models.BooleanField(default=False)

def get_remote_artifact_url(self, relative_path=None, request=None):
"""Get url for remote_artifact, content app requests need a signed pull-through token."""
"""Get url for remote_artifact, content app requests need a stored or signed entry."""
if request is None:
return super().get_remote_artifact_url(relative_path)
if not (token := request.query.get(PULL_THROUGH_PARAM)):
return None
filename = PurePath(relative_path or "").name
# pip adds ".metadata" to the end of the url (the token) instead of the url path
if token.endswith(".metadata"):
token = token.removesuffix(".metadata")
if not filename.endswith(".metadata"):
filename = f"{filename}.metadata"
setattr(self, "_real_relative_path", filename)
if resolved := unsign_pull_through_token(self, token, filename):
if token := request.query.get(PULL_THROUGH_PARAM):
# pip adds ".metadata" to the end of the url (the token) instead of the url path
if token.endswith(".metadata"):
token = token.removesuffix(".metadata")
if not filename.endswith(".metadata"):
filename = f"{filename}.metadata"
setattr(self, "_real_relative_path", filename)
resolved = unsign_pull_through_token(self, token, filename)
else:
resolved = lookup_pull_through_entry(self, filename)
if resolved:
url, sha256 = resolved
if sha256:
self.__dict__.setdefault("_pull_through_digests", {})[url] = sha256
Expand All @@ -388,7 +393,7 @@ def get_remote_artifact_content_type(self, relative_path=None):
return PythonPackageContent

def get_downloader(self, remote_artifact=None, url=None, download_factory=None, **kwargs):
"""Validate pull-through downloads against the sha256 from their signed path."""
"""Validate pull-through downloads against the sha256 from their pull-through entry."""
digests = self.__dict__.get("_pull_through_digests", {})
if remote_artifact and not remote_artifact.sha256:
remote_artifact.sha256 = digests.get(remote_artifact.url)
Expand All @@ -398,8 +403,20 @@ def get_downloader(self, remote_artifact=None, url=None, download_factory=None,

@hook(AFTER_UPDATE, when_any=["url", "includes", "excludes"], has_changed=True)
def invalidate_pull_through_cache(self):
"""Rebuild cached simple pages after the signed links they list are invalidated."""
transaction.on_commit(self.invalidate_cache)
"""Rebuild the pull-through simple pages and entries when the files they list change."""

def invalidate():
self.invalidate_cache()
clear_pull_through_entries(self.pk)

transaction.on_commit(invalidate)

@hook(BEFORE_DELETE)
def clear_pull_through_cache(self):
"""Drop the pull-through entries of a deleted remote."""
# The pk is cleared on delete before the transaction commits
remote_pk = self.pk
transaction.on_commit(lambda: clear_pull_through_entries(remote_pk))

class Meta:
default_related_name = "%(app_label)s_%(model_name)s"
Expand Down
42 changes: 28 additions & 14 deletions pulp_python/app/pypi/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
get_remote_simple_page,
python_content_to_json,
sign_pull_through_path,
store_pull_through_entries,
write_simple_detail,
write_simple_detail_json,
write_simple_index,
Expand Down Expand Up @@ -390,16 +391,21 @@ def list(self, request, path):
def pull_through_package_simple(self, package, path, remote):
"""Gets the package's simple page from remote."""

def parse_package(release_package):
def upstream_url(release_package):
parsed = urlparse(release_package.url)
stripped_url = urlunsplit(chain(parsed[:3], ("", "")))
pt_path = sign_pull_through_path(
remote,
release_package.filename,
stripped_url,
sha256=release_package.digests.get("sha256"),
metadata_sha256=(release_package.metadata_digests or {}).get("sha256"),
)
return urlunsplit(chain(parsed[:3], ("", "")))

def parse_package(release_package, stored):
if stored:
pt_path = release_package.filename
else:
pt_path = sign_pull_through_path(
remote,
release_package.filename,
upstream_url(release_package),
sha256=release_package.digests.get("sha256"),
metadata_sha256=(release_package.metadata_digests or {}).get("sha256"),
)
d_url = urljoin(self.base_content_url, f"{path}/{pt_path}")
return {
"filename": release_package.filename,
Expand All @@ -423,11 +429,19 @@ def parse_package(release_package):
if not page:
log.info(f"Failed to fetch {package} simple page from {remote.url}")
return {}
return {
p.filename: parse_package(p)
for p in page.packages
if rfilter.filter_release(package, p.version)
}
packages = [p for p in page.packages if rfilter.filter_release(package, p.version)]
stored = store_pull_through_entries(
remote,
{
p.filename: {
"url": upstream_url(p),
"sha256": p.digests.get("sha256"),
"metadata_sha256": (p.metadata_digests or {}).get("sha256"),
}
for p in packages
},
)
return {p.filename: parse_package(p, stored) for p in packages}

@extend_schema(operation_id="pypi_simple_package_read", summary="Get package simple page")
@method_decorator(cache_control(max_age=600, public=True))
Expand Down
85 changes: 83 additions & 2 deletions pulp_python/app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@
from django.db.utils import IntegrityError
from jinja2 import Template
from packaging.requirements import Requirement
from packaging.utils import canonicalize_name
from packaging.utils import canonicalize_name, parse_sdist_filename, parse_wheel_filename
from packaging.version import InvalidVersion, parse
from pypi_simple import ACCEPT_JSON_PREFERRED, ProjectPage

from pulpcore.plugin.cache import SyncContentCache
from pulpcore.plugin.exceptions import TimeoutException
from pulpcore.plugin.models import Artifact, Remote, VulnerabilityReport
from pulpcore.plugin.util import get_domain
Expand All @@ -39,6 +40,9 @@

PULL_THROUGH_PARAM = "pt"
PULL_THROUGH_SALT = "pulp_python.pull_through"
_CACHE_TTL = settings.CACHE_SETTINGS["EXPIRES_TTL"]
# Outlive both the cached simple pages and their max-age in client caches, None never expires
PULL_THROUGH_TTL = None if _CACHE_TTL is None else _CACHE_TTL + 600

PYPI_SIMPLE_V1_HTML = "application/vnd.pypi.simple.v1+html"
PYPI_SIMPLE_V1_JSON = "application/vnd.pypi.simple.v1+json"
Expand Down Expand Up @@ -776,7 +780,7 @@ async def aget_remote_simple_page(package, remote, max_retries=1):


def _pull_through_signer(remote):
# Changing what the remote lists invalidates its tokens.
# Changing what the remote lists invalidates its tokens, like it clears its stored entries
listing = json.dumps([remote.url, remote.includes, remote.excludes])
salt = f"{PULL_THROUGH_SALT}:{remote.pk}:{hashlib.sha256(listing.encode()).hexdigest()}"
return signing.Signer(salt=salt)
Expand Down Expand Up @@ -810,3 +814,80 @@ def unsign_pull_through_token(remote, token, filename):
if filename == f"{data['f']}.metadata" and data.get("m"):
return f"{data['u']}.metadata", data["m"]
return None


def _pull_through_key(remote, filename):
# Group entries per project so each expires on its own, falling back to the filename for
# legacy names that can't be parsed
try:
if filename.endswith(".whl"):
bucket = parse_wheel_filename(filename)[0]
else:
bucket = parse_sdist_filename(filename)[0]
except ValueError:
bucket = filename
return f"pulp_python:pull_through:{remote.pk}:{bucket}"


def store_pull_through_entries(remote, entries):
"""
Stores filename -> {url, sha256, metadata_sha256} entries of a remote in Redis.

Returns True if the entries were stored, so plain filename links can be used for them.
"""
if not settings.CACHE_ENABLED:
return False
if not entries:
return True
buckets = defaultdict(dict)
for filename, entry in entries.items():
buckets[_pull_through_key(remote, filename)][filename] = json.dumps(entry)
try:
pipe = SyncContentCache().redis.pipeline(transaction=False)
for key, mapping in buckets.items():
pipe.hset(key, mapping=mapping)
if PULL_THROUGH_TTL is not None:
pipe.expire(key, PULL_THROUGH_TTL)
pipe.execute()
except Exception as e:
log.warning("Failed to store pull-through entries: %s", e)
return False
return True


def clear_pull_through_entries(remote_pk):
"""Deletes all the stored pull-through entries of a remote."""
if not settings.CACHE_ENABLED:
return
try:
redis = SyncContentCache().redis
keys = list(redis.scan_iter(match=f"pulp_python:pull_through:{remote_pk}:*", count=1000))
if keys:
redis.delete(*keys)
except Exception as e:
log.warning("Failed to clear pull-through entries: %s", e)


def lookup_pull_through_entry(remote, filename):
"""
Returns the upstream (url, sha256) for a file stored by store_pull_through_entries.

filename can be a stored package's filename or its PEP 658 metadata file.
"""
if not settings.CACHE_ENABLED:
return None
is_metadata = filename.endswith(".metadata")
filename = filename.removesuffix(".metadata")
try:
raw = SyncContentCache().redis.hget(_pull_through_key(remote, filename), filename)
except Exception as e:
log.warning("Failed to look up pull-through entry: %s", e)
return None
if not raw:
return None
entry = json.loads(raw)
if not is_metadata:
return entry["url"], entry.get("sha256")
if entry.get("metadata_sha256"):
return f"{entry['url']}.metadata", entry["metadata_sha256"]
return None
Loading
Loading