-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathmodels.py
More file actions
420 lines (356 loc) · 14.9 KB
/
models.py
File metadata and controls
420 lines (356 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import hashlib
import json
from logging import getLogger
from aiohttp.web import json_response
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.conf import settings
from django_lifecycle import (
BEFORE_SAVE,
hook,
)
from rest_framework.serializers import ValidationError
from pulpcore.plugin.models import (
AutoAddObjPermsMixin,
Content,
Publication,
Distribution,
Remote,
Repository,
)
from pulpcore.plugin.responses import ArtifactResponse
from pathlib import PurePath
from .provenance import Provenance
from .utils import (
artifact_to_python_content_data,
artifact_to_metadata_artifact,
canonicalize_name,
python_content_to_json,
PYPI_LAST_SERIAL,
PYPI_SERIAL_CONSTANT,
)
from pulpcore.plugin.repo_version_utils import (
collect_duplicates,
remove_duplicates,
validate_repo_version,
)
from pulpcore.plugin.util import get_domain_pk, get_domain
log = getLogger(__name__)
PACKAGE_TYPES = (
("bdist_dmg", "bdist_dmg"),
("bdist_dumb", "bdist_dumb"),
("bdist_egg", "bdist_egg"),
("bdist_msi", "bdist_msi"),
("bdist_rpm", "bdist_rpm"),
("bdist_wheel", "bdist_wheel"),
("bdist_wininst", "bdist_wininst"),
("sdist", "sdist"),
)
PLATFORMS = (
("windows", "windows"),
("macos", "macos"),
("freebsd", "freebsd"),
("linux", "linux"),
)
class PythonDistribution(Distribution, AutoAddObjPermsMixin):
"""
Distribution for 'Python' Content.
"""
TYPE = "python"
allow_uploads = models.BooleanField(default=True)
def content_handler(self, path):
"""
Handler to serve extra, non-Artifact content for this Distribution
Args:
path (str): The path being requested
Returns:
None if there is no content to be served at path. Otherwise a
aiohttp.web_response.Response with the content.
"""
path = PurePath(path)
name = None
version = None
domain = get_domain()
if path.match("pypi/*/*/json"):
version = path.parts[2]
name = path.parts[1]
elif path.match("pypi/*/json"):
name = path.parts[1]
elif len(path.parts) and path.parts[0] == "simple":
# Temporary fix for PublishedMetadata not being properly served from remote storage
# https://github.com/pulp/pulp_python/issues/413
if domain.storage_class != "pulpcore.app.models.storage.FileSystem":
if self.publication or self.repository:
try:
publication = self.publication or Publication.objects.filter(
repository_version=self.repository.latest_version()
).latest("pulp_created")
except ObjectDoesNotExist:
return None
if len(path.parts) == 2:
path = PurePath(f"simple/{canonicalize_name(path.parts[1])}")
rel_path = f"{path}/index.html"
try:
ca = (
publication.published_artifact.select_related(
"content_artifact",
"content_artifact__artifact",
)
.get(relative_path=rel_path)
.content_artifact
)
except ObjectDoesNotExist:
return None
headers = {"Content-Type": "text/html"}
return ArtifactResponse(ca.artifact, headers=headers)
if name:
normalized = canonicalize_name(name)
package_content = PythonPackageContent.objects.filter(
pk__in=self.publication.repository_version.content, name_normalized=normalized
)
# TODO Change this value to the Repo's serial value when implemented
headers = {PYPI_LAST_SERIAL: str(PYPI_SERIAL_CONSTANT)}
if not settings.DOMAIN_ENABLED:
domain = None
json_body = python_content_to_json(
self.base_path, package_content, version=version, domain=domain
)
if json_body:
return json_response(json_body, headers=headers)
return None
class Meta:
default_related_name = "%(app_label)s_%(model_name)s"
permissions = [
("manage_roles_pythondistribution", "Can manage roles on python distributions"),
]
class PythonPackageContent(Content):
"""
A Content Type representing Python's Distribution Package.
Core Metadata:
https://packaging.python.org/en/latest/specifications/core-metadata/
Release metadata (JSON API):
https://docs.pypi.org/api/json/
File Formats:
https://packaging.python.org/en/latest/specifications/source-distribution-format/
https://packaging.python.org/en/latest/specifications/binary-distribution-format/
"""
# Core metadata
# Version 1.0
author = models.TextField()
author_email = models.TextField()
description = models.TextField()
home_page = models.TextField() # Deprecated in favour of Project-URL
keywords = models.TextField()
license = models.TextField() # Deprecated in favour of License-Expression
metadata_version = models.TextField()
name = models.TextField()
platform = models.TextField()
summary = models.TextField()
version = models.TextField()
# Version 1.1
classifiers = models.JSONField(default=list)
download_url = models.TextField() # Deprecated in favour of Project-URL
supported_platform = models.TextField()
# Version 1.2
maintainer = models.TextField()
maintainer_email = models.TextField()
obsoletes_dist = models.JSONField(default=list)
project_url = models.TextField()
project_urls = models.JSONField(default=dict)
provides_dist = models.JSONField(default=list)
requires_external = models.JSONField(default=list)
requires_dist = models.JSONField(default=list)
requires_python = models.TextField()
# Version 2.1
description_content_type = models.TextField()
provides_extras = models.JSONField(default=list)
# Version 2.2
dynamic = models.JSONField(default=list)
# Version 2.4
license_expression = models.TextField()
license_file = models.JSONField(default=list)
# Stored normalized name for indexed lookups
name_normalized = models.TextField(db_index=True, default="")
# Release metadata
filename = models.TextField(db_index=True)
packagetype = models.TextField(choices=PACKAGE_TYPES)
python_version = models.TextField()
sha256 = models.CharField(db_index=True, max_length=64)
metadata_sha256 = models.CharField(max_length=64, null=True)
size = models.BigIntegerField(default=0)
# yanked and yanked_reason are not implemented because they are mutable
# From pulpcore
PROTECTED_FROM_RECLAIM = False
TYPE = "python"
_pulp_domain = models.ForeignKey("core.Domain", default=get_domain_pk, on_delete=models.PROTECT)
repo_key_fields = ("filename",)
@hook(BEFORE_SAVE)
def set_name_normalized(self):
"""Pre-compute the normalized package name for indexed lookups."""
self.name_normalized = canonicalize_name(self.name)
@staticmethod
def init_from_artifact_and_relative_path(artifact, relative_path):
"""Used when downloading package from pull-through cache."""
path = PurePath(relative_path)
data = artifact_to_python_content_data(path.name, artifact, domain=get_domain())
artifacts = {path.name: artifact}
if metadata_artifact := artifact_to_metadata_artifact(path.name, artifact):
artifacts[f"{path.name}.metadata"] = metadata_artifact
return PythonPackageContent(**data), artifacts
def __str__(self):
"""
Provide more useful repr information.
Overrides Content.str to provide the distribution version and type at
the end.
e.g. <PythonPackageContent: shelf-reader [version] (whl)>
"""
return "<{obj_name}: {name} [{version}] ({type})>".format(
obj_name=self._meta.object_name,
name=self.name,
version=self.version,
type=self.packagetype,
)
class Meta:
default_related_name = "%(app_label)s_%(model_name)s"
unique_together = ("sha256", "_pulp_domain")
permissions = [
("upload_python_packages", "Can upload Python packages using synchronous API."),
]
class PackageProvenance(Content):
"""
PEP 740 provenance objects.
"""
TYPE = "provenance"
repo_key_fields = ("package_id",)
package = models.ForeignKey(
PythonPackageContent, on_delete=models.CASCADE, related_name="provenances"
)
provenance = models.JSONField(null=False)
sha256 = models.CharField(max_length=64, null=False)
_pulp_domain = models.ForeignKey("core.Domain", default=get_domain_pk, on_delete=models.PROTECT)
@staticmethod
def calculate_sha256(provenance):
"""Calculates the sha256 from the provenance."""
provenance_json = json.dumps(provenance, sort_keys=True).encode("utf-8")
hasher = hashlib.sha256(provenance_json)
return hasher.hexdigest()
@hook(BEFORE_SAVE)
def set_sha256_hook(self):
"""Ensure that sha256 is set before saving."""
self.sha256 = self.calculate_sha256(self.provenance)
@property
def as_model(self):
return Provenance.model_validate(self.provenance)
class Meta:
default_related_name = "%(app_label)s_%(model_name)s"
unique_together = ("sha256", "_pulp_domain")
class PythonPublication(Publication, AutoAddObjPermsMixin):
"""
A Publication for PythonContent.
"""
TYPE = "python"
class Meta:
default_related_name = "%(app_label)s_%(model_name)s"
permissions = [
("manage_roles_pythonpublication", "Can manage roles on python publications"),
]
class PythonRemote(Remote, AutoAddObjPermsMixin):
"""
A Remote for Python Content.
Fields:
prereleases (models.BooleanField): Whether to sync pre-release versions of packages.
"""
TYPE = "python"
DEFAULT_DOWNLOAD_CONCURRENCY = 10
prereleases = models.BooleanField(default=False)
includes = models.JSONField(default=list)
excludes = models.JSONField(default=list)
package_types = ArrayField(
models.CharField(max_length=15, blank=True), choices=PACKAGE_TYPES, default=list
)
keep_latest_packages = models.IntegerField(default=0)
exclude_platforms = ArrayField(
models.CharField(max_length=10, blank=True), choices=PLATFORMS, default=list
)
provenance = models.BooleanField(default=False)
def get_remote_artifact_url(self, relative_path=None, request=None):
"""Get url for remote_artifact"""
if request and (url := request.query.get("redirect")):
# This is a special case for pull-through caching
# To handle PEP 658, it states that if the package has metadata available then it
# should be found at the download URL + ".metadata". Thus if the request url ends with
# ".metadata" then we need to add ".metadata" to the redirect url if not present.
if relative_path:
if relative_path.endswith(".metadata") and not url.endswith(".metadata"):
url += ".metadata"
# Handle special case for bug in pip (TODO file issue in pip) where it appends
# ".metadata" to the redirect url instead of the request url
if url.endswith(".metadata") and not relative_path.endswith(".metadata"):
setattr(self, "_real_relative_path", url.rsplit("/", 1)[1])
return url
return super().get_remote_artifact_url(relative_path, request=request)
def get_remote_artifact_content_type(self, relative_path=None):
"""Return PythonPackageContent, except for metadata artifacts."""
if hasattr(self, "_real_relative_path"):
relative_path = getattr(self, "_real_relative_path")
if relative_path and relative_path.endswith(".whl.metadata"):
return None
return PythonPackageContent
class Meta:
default_related_name = "%(app_label)s_%(model_name)s"
permissions = [
("manage_roles_pythonremote", "Can manage roles on python remotes"),
]
class PythonRepository(Repository, AutoAddObjPermsMixin):
"""
Repository for "python" content.
"""
TYPE = "python"
CONTENT_TYPES = [PythonPackageContent, PackageProvenance]
REMOTE_TYPES = [PythonRemote]
PULL_THROUGH_SUPPORTED = True
autopublish = models.BooleanField(default=False)
allow_package_substitution = models.BooleanField(default=True)
class Meta:
default_related_name = "%(app_label)s_%(model_name)s"
permissions = [
("sync_pythonrepository", "Can start a sync task"),
("modify_pythonrepository", "Can modify content of the repository"),
("manage_roles_pythonrepository", "Can manage roles on python repositories"),
("repair_pythonrepository", "Can repair repository versions"),
]
def on_new_version(self, version):
"""
Called when new repository versions are created.
Args:
version: The new repository version
"""
super().on_new_version(version)
# avoid circular import issues
from pulp_python.app import tasks
if self.autopublish:
tasks.publish(repository_version_pk=version.pk)
def finalize_new_version(self, new_version):
"""
Remove duplicate packages that have the same filename.
When allow_package_substitution is False, reject any new version that would implicitly
replace existing content with different checksums (content substitution).
"""
if not self.allow_package_substitution:
self._check_for_package_substitution(new_version)
remove_duplicates(new_version)
validate_repo_version(new_version)
def _check_for_package_substitution(self, new_version):
"""
Raise a ValidationError if newly added packages would replace existing packages that have
the same filename but a different sha256 checksum.
"""
qs = PythonPackageContent.objects.filter(pk__in=new_version.content)
duplicates = collect_duplicates(qs, ("filename",))
if duplicates:
raise ValidationError(
"Found duplicate packages being added with the same filename but different checksums. " # noqa: E501
"To allow this, set 'allow_package_substitution' to True on the repository. "
f"Conflicting packages: {duplicates}"
)