Skip to content

Commit 69e1326

Browse files
committed
Create and expose metadata file
1 parent 37626da commit 69e1326

File tree

12 files changed

+417
-16
lines changed

12 files changed

+417
-16
lines changed

pulp_python/app/management/commands/repair-python-metadata.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,14 @@ def repair_metadata(content):
2424
set_of_update_fields = set()
2525
total_repaired = 0
2626
for package in immediate_content.prefetch_related("_artifacts").iterator(chunk_size=1000):
27+
# Get the main artifact
28+
main_artifact = (
29+
package.contentartifact_set.exclude(relative_path__endswith=".metadata")
30+
.first()
31+
.artifact
32+
)
2733
new_data = artifact_to_python_content_data(
28-
package.filename, package._artifacts.get(), package.pulp_domain
34+
package.filename, main_artifact, package.pulp_domain
2935
)
3036
changed = False
3137
for field, value in new_data.items():
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# Generated manually on 2025-12-15 14:00 for creating missing metadata artifacts
2+
3+
from django.db import migrations
4+
5+
6+
def extract_wheel_metadata(filename):
7+
"""
8+
Extract the metadata file content from a wheel file.
9+
Returns the raw metadata content as bytes or None if metadata cannot be extracted.
10+
"""
11+
import zipfile
12+
13+
if not filename.endswith(".whl"):
14+
return None
15+
try:
16+
with zipfile.ZipFile(filename, "r") as f:
17+
for file_path in f.namelist():
18+
if file_path.endswith(".dist-info/METADATA"):
19+
return f.read(file_path)
20+
except (zipfile.BadZipFile, KeyError, OSError):
21+
pass
22+
return None
23+
24+
25+
def artifact_to_metadata_artifact(filename, artifact, tmp_dir, artifact_model, get_domain):
26+
"""
27+
Creates artifact for metadata from the provided wheel artifact.
28+
"""
29+
import os
30+
import shutil
31+
import tempfile
32+
from django.db import IntegrityError
33+
34+
if not filename.endswith(".whl"):
35+
return None
36+
37+
temp_wheel_path = None
38+
temp_metadata_path = None
39+
try:
40+
with tempfile.NamedTemporaryFile(
41+
"wb", dir=tmp_dir, suffix=filename, delete=False
42+
) as temp_file:
43+
temp_wheel_path = temp_file.name
44+
artifact.file.seek(0)
45+
shutil.copyfileobj(artifact.file, temp_file)
46+
temp_file.flush()
47+
48+
metadata_content = extract_wheel_metadata(temp_wheel_path)
49+
if not metadata_content:
50+
return None
51+
52+
with tempfile.NamedTemporaryFile(
53+
"wb", dir=tmp_dir, suffix=".metadata", delete=False
54+
) as temp_md:
55+
temp_metadata_path = temp_md.name
56+
temp_md.write(metadata_content)
57+
temp_md.flush()
58+
59+
metadata_artifact = artifact_model.init_and_validate(temp_metadata_path)
60+
try:
61+
metadata_artifact.save()
62+
except IntegrityError:
63+
metadata_artifact = artifact_model.objects.get(
64+
sha256=metadata_artifact.sha256, pulp_domain=get_domain()
65+
)
66+
return metadata_artifact
67+
68+
finally:
69+
if temp_wheel_path and os.path.exists(temp_wheel_path):
70+
os.unlink(temp_wheel_path)
71+
if temp_metadata_path and os.path.exists(temp_metadata_path):
72+
os.unlink(temp_metadata_path)
73+
74+
75+
def create_missing_metadata_artifacts(apps, schema_editor):
76+
"""
77+
Create metadata artifacts for PythonPackageContent instances that have metadata_sha256
78+
but are missing the corresponding metadata artifact.
79+
"""
80+
import tempfile
81+
from pulpcore.plugin.util import get_domain
82+
83+
PythonPackageContent = apps.get_model("python", "PythonPackageContent")
84+
ContentArtifact = apps.get_model("core", "ContentArtifact")
85+
Artifact = apps.get_model("core", "Artifact")
86+
87+
packages = (
88+
PythonPackageContent.objects.filter(metadata_sha256__isnull=False)
89+
.exclude(metadata_sha256="")
90+
.prefetch_related("contentartifact_set")
91+
)
92+
created_count = 0
93+
skipped_count = 0
94+
95+
with tempfile.TemporaryDirectory() as temp_dir:
96+
for package in packages:
97+
metadata_relative_path = f"{package.filename}.metadata"
98+
content_artifacts = list(package.contentartifact_set.all())
99+
100+
if any(ca.relative_path == metadata_relative_path for ca in content_artifacts):
101+
# Metadata artifact already exist
102+
continue
103+
104+
main_content_artifact = next(
105+
(ca for ca in content_artifacts if ca.relative_path == package.filename),
106+
None,
107+
)
108+
if not main_content_artifact:
109+
# Main artifact does not exist
110+
skipped_count += 1
111+
continue
112+
113+
metadata_artifact = artifact_to_metadata_artifact(
114+
package.filename, main_content_artifact.artifact, temp_dir, Artifact, get_domain
115+
)
116+
if not metadata_artifact:
117+
# Failed to create metadata artifact
118+
skipped_count += 1
119+
continue
120+
121+
ContentArtifact.objects.create(
122+
artifact=metadata_artifact, content=package, relative_path=metadata_relative_path
123+
)
124+
created_count += 1
125+
126+
print(f"Created {created_count} missing metadata artifacts. Skipped {skipped_count} packages.")
127+
128+
129+
class Migration(migrations.Migration):
130+
131+
dependencies = [
132+
("python", "0018_packageprovenance"),
133+
]
134+
135+
operations = [
136+
migrations.RunPython(
137+
create_missing_metadata_artifacts,
138+
reverse_code=migrations.RunPython.noop,
139+
),
140+
]

pulp_python/app/serializers.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
22
import os
3+
import tempfile
34
from gettext import gettext as _
45
from django.conf import settings
56
from django.db.utils import IntegrityError
@@ -22,6 +23,7 @@
2223
)
2324
from pulp_python.app.utils import (
2425
DIST_EXTENSIONS,
26+
artifact_to_metadata_artifact,
2527
artifact_to_python_content_data,
2628
get_project_metadata_from_file,
2729
parse_project_metadata,
@@ -93,11 +95,31 @@ class Meta:
9395
model = python_models.PythonDistribution
9496

9597

98+
class PythonSingleContentArtifactField(core_serializers.SingleContentArtifactField):
99+
"""
100+
Custom field with overridden get_attribute method. Meant to be used only in
101+
PythonPackageContentSerializer to handle possible existence of metadata artifact.
102+
"""
103+
104+
def get_attribute(self, instance):
105+
# When content has multiple artifacts (wheel + metadata), return the main one
106+
if instance._artifacts.count() > 1:
107+
for ca in instance.contentartifact_set.all():
108+
if not ca.relative_path.endswith(".metadata"):
109+
return ca.artifact
110+
111+
return super().get_attribute(instance)
112+
113+
96114
class PythonPackageContentSerializer(core_serializers.SingleArtifactContentUploadSerializer):
97115
"""
98116
A Serializer for PythonPackageContent.
99117
"""
100118

119+
artifact = PythonSingleContentArtifactField(
120+
help_text=_("Artifact file representing the physical content"),
121+
)
122+
101123
# Core metadata
102124
# Version 1.0
103125
author = serializers.CharField(
@@ -386,8 +408,21 @@ def deferred_validate(self, data):
386408
if attestations := data.pop("attestations", None):
387409
data["provenance"] = self.handle_attestations(filename, data["sha256"], attestations)
388410

411+
# Create metadata artifact for wheel files
412+
if filename.endswith(".whl"):
413+
if metadata_artifact := artifact_to_metadata_artifact(filename, artifact):
414+
data["metadata_artifact"] = metadata_artifact
415+
data["metadata_sha256"] = metadata_artifact.sha256
416+
389417
return data
390418

419+
def get_artifacts(self, validated_data):
420+
artifacts = super().get_artifacts(validated_data)
421+
if metadata_artifact := validated_data.pop("metadata_artifact", None):
422+
relative_path = f"{validated_data['filename']}.metadata"
423+
artifacts[relative_path] = metadata_artifact
424+
return artifacts
425+
391426
def retrieve(self, validated_data):
392427
content = python_models.PythonPackageContent.objects.filter(
393428
sha256=validated_data["sha256"], _pulp_domain=get_domain()
@@ -419,6 +454,7 @@ def create(self, validated_data):
419454

420455
class Meta:
421456
fields = core_serializers.SingleArtifactContentUploadSerializer.Meta.fields + (
457+
"artifact",
422458
"author",
423459
"author_email",
424460
"description",
@@ -514,6 +550,15 @@ def validate(self, data):
514550
data["provenance"] = self.handle_attestations(
515551
filename, data["sha256"], attestations, offline=True
516552
)
553+
# Create metadata artifact for wheel files
554+
if filename.endswith(".whl"):
555+
with tempfile.TemporaryDirectory(dir=settings.WORKING_DIRECTORY) as temp_dir:
556+
if metadata_artifact := artifact_to_metadata_artifact(
557+
filename, artifact, tmp_dir=temp_dir
558+
):
559+
data["metadata_artifact"] = metadata_artifact
560+
data["metadata_sha256"] = metadata_artifact.sha256
561+
517562
return data
518563

519564
class Meta(PythonPackageContentSerializer.Meta):

pulp_python/app/tasks/repair.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,13 @@ def repair_metadata(content: QuerySet[PythonPackageContent]) -> tuple[int, set[s
9595
progress_report.save()
9696
with progress_report:
9797
for package in progress_report.iter(immediate_content.iterator(chunk_size=BULK_SIZE)):
98-
new_data = artifact_to_python_content_data(
99-
package.filename, package._artifacts.get(), domain
98+
# Get the main artifact
99+
main_artifact = (
100+
package.contentartifact_set.exclude(relative_path__endswith=".metadata")
101+
.first()
102+
.artifact
100103
)
104+
new_data = artifact_to_python_content_data(package.filename, main_artifact, domain)
101105
total_repaired += update_package_if_needed(
102106
package, new_data, batch, set_of_update_fields
103107
)
@@ -113,7 +117,11 @@ def repair_metadata(content: QuerySet[PythonPackageContent]) -> tuple[int, set[s
113117
grouped_by_url = defaultdict(list)
114118

115119
for package in group_set:
116-
for ra in package.contentartifact_set.get().remoteartifact_set.all():
120+
for ra in (
121+
package.contentartifact_set.exclude(relative_path__endswith=".metadata")
122+
.first()
123+
.remoteartifact_set.all()
124+
):
117125
grouped_by_url[ra.remote.url].append((package, ra))
118126

119127
# Prioritize the URL that can serve the most packages

pulp_python/app/tasks/sync.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,11 +229,15 @@ async def create_content(self, pkg):
229229
create a Content Unit to put into the pipeline
230230
"""
231231
declared_contents = {}
232+
page = await aget_remote_simple_page(pkg.name, self.remote)
233+
upstream_pkgs = {pkg.filename: pkg for pkg in page.packages}
234+
232235
for version, dists in pkg.releases.items():
233236
for package in dists:
234237
entry = parse_metadata(pkg.info, version, package)
235238
url = entry.pop("url")
236239
size = package["size"] or None
240+
d_artifacts = []
237241

238242
artifact = Artifact(sha256=entry["sha256"], size=size)
239243
package = PythonPackageContent(**entry)
@@ -245,11 +249,28 @@ async def create_content(self, pkg):
245249
remote=self.remote,
246250
deferred_download=self.deferred_download,
247251
)
248-
dc = DeclarativeContent(content=package, d_artifacts=[da])
252+
d_artifacts.append(da)
253+
254+
if upstream_pkg := upstream_pkgs.get(entry["filename"]):
255+
if upstream_pkg.has_metadata:
256+
url = upstream_pkg.metadata_url
257+
md_sha256 = upstream_pkg.metadata_digests.get("sha256")
258+
artifact = Artifact(sha256=md_sha256)
259+
260+
metadata_artifact = DeclarativeArtifact(
261+
artifact=artifact,
262+
url=url,
263+
relative_path=f"{entry['filename']}.metadata",
264+
remote=self.remote,
265+
deferred_download=self.deferred_download,
266+
)
267+
d_artifacts.append(metadata_artifact)
268+
269+
dc = DeclarativeContent(content=package, d_artifacts=d_artifacts)
249270
declared_contents[entry["filename"]] = dc
250271
await self.python_stage.put(dc)
251272

252-
if pkg.releases and (page := await aget_remote_simple_page(pkg.name, self.remote)):
273+
if pkg.releases and page:
253274
if self.remote.provenance:
254275
await self.sync_provenance(page, declared_contents)
255276

pulp_python/app/tasks/upload.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
Provenance,
1616
verify_provenance,
1717
)
18-
from pulp_python.app.utils import artifact_to_python_content_data
18+
from pulp_python.app.utils import artifact_to_metadata_artifact, artifact_to_python_content_data
1919

2020

2121
def upload(artifact_sha256, filename, attestations=None, repository_pk=None):
@@ -97,6 +97,11 @@ def create_content(artifact_sha256, filename, domain):
9797
def create():
9898
content = PythonPackageContent.objects.create(**data)
9999
ContentArtifact.objects.create(artifact=artifact, content=content, relative_path=filename)
100+
101+
if metadata_artifact := artifact_to_metadata_artifact(filename, artifact):
102+
ContentArtifact.objects.create(
103+
artifact=metadata_artifact, content=content, relative_path=f"{filename}.metadata"
104+
)
100105
return content
101106

102107
new_content = create()

0 commit comments

Comments
 (0)