Skip to content

Commit 375bf2f

Browse files
committed
Add include/exclude filter support for pull-through caching
fixes: #706
1 parent 0f92af4 commit 375bf2f

File tree

5 files changed

+153
-22
lines changed

5 files changed

+153
-22
lines changed

CHANGES/706.feature

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Pull-through caching now respects the include/exclude filters on the upstream remote.

docs/user/guides/publish.md

+3
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,9 @@ from the remote source and have Pulp store that package as orphaned content.
8888
pulp python distribution update --name foo --remote bar
8989
```
9090

91+
!!! note
92+
Pull-through caching will respect the includes/excludes filters on the supplied remote.
93+
9194
!!! warning
9295
Support for pull-through caching is provided as a tech preview in Pulp 3.
9396
Functionality may not work or may be incomplete. Also, backwards compatibility when upgrading

pulp_python/app/pypi/views.py

+31-21
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
import json
12
import logging
2-
import requests
3+
import os
34

45
from rest_framework.viewsets import ViewSet
56
from rest_framework.response import Response
@@ -15,15 +16,16 @@
1516
Http404,
1617
HttpResponseForbidden,
1718
HttpResponseBadRequest,
18-
StreamingHttpResponse
19+
StreamingHttpResponse,
20+
HttpResponse,
1921
)
2022
from drf_spectacular.utils import extend_schema
2123
from dynaconf import settings
2224
from itertools import chain
2325
from packaging.utils import canonicalize_name
2426
from urllib.parse import urljoin, urlparse, urlunsplit
2527
from pathlib import PurePath
26-
from pypi_simple import parse_links_stream_response
28+
from pypi_simple import ACCEPT_JSON_PREFERRED, ProjectPage
2729

2830
from pulpcore.plugin.viewsets import OperationPostponedResponse
2931
from pulpcore.plugin.tasking import dispatch
@@ -45,6 +47,7 @@
4547
python_content_to_json,
4648
PYPI_LAST_SERIAL,
4749
PYPI_SERIAL_CONSTANT,
50+
get_remote_package_filter,
4851
)
4952

5053
from pulp_python.app import tasks
@@ -232,27 +235,34 @@ def list(self, request, path):
232235

233236
def pull_through_package_simple(self, package, path, remote):
234237
"""Gets the package's simple page from remote."""
235-
def parse_url(link):
236-
parsed = urlparse(link.url)
237-
digest, _, value = parsed.fragment.partition('=')
238+
def parse_package(dis_package):
239+
parsed = urlparse(dis_package.url)
238240
stripped_url = urlunsplit(chain(parsed[:3], ("", "")))
239-
redirect = f'{path}/{link.text}?redirect={stripped_url}'
240-
d_url = urljoin(self.base_content_url, redirect)
241-
return link.text, d_url, value if digest == 'sha256' else ''
241+
redirect_path = f'{path}/{dis_package.filename}?redirect={stripped_url}'
242+
d_url = urljoin(self.base_content_url, redirect_path)
243+
return dis_package.filename, d_url, dis_package.digests.get("sha256", "")
244+
245+
rfilter = get_remote_package_filter(remote)
246+
if not rfilter.filter_project(package):
247+
raise Http404(f"{package} does not exist.")
242248

243249
url = remote.get_remote_artifact_url(f'simple/{package}/')
244-
kwargs = {}
245-
if proxy_url := remote.proxy_url:
246-
if remote.proxy_username or remote.proxy_password:
247-
parsed_proxy = urlparse(proxy_url)
248-
netloc = f"{remote.proxy_username}:{remote.proxy_password}@{parsed_proxy.netloc}"
249-
proxy_url = urlunsplit((parsed_proxy.scheme, netloc, "", "", ""))
250-
kwargs["proxies"] = {"http": proxy_url, "https": proxy_url}
251-
252-
response = requests.get(url, stream=True, **kwargs)
253-
links = parse_links_stream_response(response)
254-
packages = (parse_url(link) for link in links)
255-
return StreamingHttpResponse(write_simple_detail(package, packages, streamed=True))
250+
remote.headers = remote.headers or []
251+
remote.headers.append({"Accept": ACCEPT_JSON_PREFERRED})
252+
downloader = remote.get_downloader(url=url, max_retries=1)
253+
try:
254+
d = downloader.fetch()
255+
except Exception:
256+
raise Http404(f"Could not find {package}.")
257+
258+
if d.headers["content-type"] == "application/vnd.pypi.simple.v1+json":
259+
page = ProjectPage.from_json_data(json.load(open(d.path, "rb")), base_url=remote.url)
260+
else:
261+
page = ProjectPage.from_html(package, open(d.path, "rb").read(), base_url=remote.url)
262+
packages = [
263+
parse_package(p) for p in page.packages if rfilter.filter_release(package, p.version)
264+
]
265+
return HttpResponse(write_simple_detail(package, packages))
256266

257267
@extend_schema(operation_id="pypi_simple_package_read", summary="Get package simple page")
258268
def retrieve(self, request, path, package):

pulp_python/app/utils.py

+77-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
from django.conf import settings
77
from jinja2 import Template
88
from packaging.utils import canonicalize_name
9-
from packaging.version import parse
9+
from packaging.requirements import Requirement
10+
from packaging.version import parse, InvalidVersion
1011

1112

1213
PYPI_LAST_SERIAL = "X-PYPI-LAST-SERIAL"
@@ -317,3 +318,78 @@ def write_simple_detail(project_name, project_packages, streamed=False):
317318
detail = Template(simple_detail_template)
318319
context = {"project_name": project_name, "project_packages": project_packages}
319320
return detail.stream(**context) if streamed else detail.render(**context)
321+
322+
323+
class PackageIncludeFilter:
324+
"""A special class to help filter Package's based on a remote's include/exclude"""
325+
326+
def __init__(self, remote):
327+
self.remote = remote.cast()
328+
self._filter_includes = self._parse_packages(self.remote.includes)
329+
self._filter_excludes = self._parse_packages(self.remote.excludes)
330+
331+
def _parse_packages(self, packages):
332+
config = defaultdict(lambda: defaultdict(list))
333+
for value in packages:
334+
requirement = Requirement(value)
335+
requirement.name = canonicalize_name(requirement.name)
336+
if requirement.specifier:
337+
requirement.specifier.prereleases = True
338+
config["range"][requirement.name].append(requirement)
339+
else:
340+
config["full"][requirement.name].append(requirement)
341+
return config
342+
343+
def filter_project(self, project_name):
344+
"""Return true/false if project_name would be allowed through remote's filters."""
345+
project_name = canonicalize_name(project_name)
346+
include_full = self._filter_includes.get("full", {})
347+
include_range = self._filter_includes.get("range", {})
348+
include = set(include_range.keys()).union(include_full.keys())
349+
if include and project_name not in include:
350+
return False
351+
352+
exclude_full = self._filter_excludes.get("full", {})
353+
if project_name in exclude_full:
354+
return False
355+
356+
return True
357+
358+
def filter_release(self, project_name, version):
359+
"""Returns true/false if release would be allowed through remote's filters."""
360+
project_name = canonicalize_name(project_name)
361+
if not self.filter_project(project_name):
362+
return False
363+
364+
try:
365+
version = parse(version)
366+
except InvalidVersion:
367+
return False
368+
369+
include_range = self._filter_includes.get("range", {})
370+
if project_name in include_range:
371+
for req in include_range[project_name]:
372+
if version in req.specifier:
373+
break
374+
else:
375+
return False
376+
377+
exclude_range = self._filter_excludes.get("range", {})
378+
if project_name in exclude_range:
379+
for req in exclude_range[project_name]:
380+
if version in req.specifier:
381+
return False
382+
383+
return True
384+
385+
386+
_remote_filters = {}
387+
def get_remote_package_filter(remote):
388+
if date_filter_tuple := _remote_filters.get(remote.pulp_id):
389+
last_update, rfilter = date_filter_tuple
390+
if last_update == remote.pulp_last_updated:
391+
return rfilter
392+
393+
rfilter = PackageIncludeFilter(remote)
394+
_remote_filters[remote.pulp_id] = (remote.pulp_last_updated, rfilter)
395+
return rfilter

pulp_python/tests/functional/api/test_full_mirror.py

+41
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,12 @@
55
from pulp_python.tests.functional.constants import (
66
PYPI_URL,
77
PYTHON_XS_FIXTURE_CHECKSUMS,
8+
PYTHON_SM_PROJECT_SPECIFIER,
9+
PYTHON_SM_FIXTURE_RELEASES,
810
)
911

1012
from pypi_simple import ProjectPage
13+
from packaging.version import parse
1114
from urllib.parse import urljoin, urlsplit
1215

1316

@@ -54,6 +57,44 @@ def test_pull_through_simple(python_remote_factory, python_distribution_factory,
5457
assert PYTHON_XS_FIXTURE_CHECKSUMS[package.filename] == package.digests["sha256"]
5558

5659

60+
@pytest.mark.parallel
61+
def test_pull_through_filter(python_remote_factory, python_distribution_factory):
62+
"""Tests that pull-through respects the includes/excludes filter on the remote."""
63+
remote = python_remote_factory(url=PYPI_URL, includes=["shelf-reader"])
64+
distro = python_distribution_factory(remote=remote.pulp_href)
65+
66+
r = requests.get(f"{distro.base_url}simple/pulpcore/")
67+
assert r.status_code == 404
68+
assert r.json() == {'detail': 'pulpcore does not exist.'}
69+
70+
r = requests.get(f"{distro.base_url}simple/shelf-reader/")
71+
assert r.status_code == 200
72+
73+
# Test complex include specifiers
74+
remote = python_remote_factory(includes=PYTHON_SM_PROJECT_SPECIFIER)
75+
distro = python_distribution_factory(remote=remote.pulp_href)
76+
for package, releases in PYTHON_SM_FIXTURE_RELEASES.items():
77+
url = f"{distro.base_url}simple/{package}/"
78+
project_page = ProjectPage.from_response(requests.get(url), package)
79+
packages = {p.filename for p in project_page.packages if not parse(p.version).is_prerelease}
80+
assert packages == set(releases)
81+
82+
# Test exclude logic
83+
remote = python_remote_factory(includes=[], excludes=["django"])
84+
distro = python_distribution_factory(remote=remote.pulp_href)
85+
86+
r = requests.get(f"{distro.base_url}simple/django/")
87+
assert r.status_code == 404
88+
assert r.json() == {'detail': 'django does not exist.'}
89+
90+
r = requests.get(f"{distro.base_url}simple/pulpcore/")
91+
assert r.status_code == 404
92+
assert r.json() == {'detail': 'Could not find pulpcore.'}
93+
94+
r = requests.get(f"{distro.base_url}simple/shelf-reader/")
95+
assert r.status_code == 200
96+
97+
5798
@pytest.mark.parallel
5899
def test_pull_through_with_repo(
59100
python_repo_with_sync, python_remote_factory, python_distribution_factory

0 commit comments

Comments
 (0)