forked from pulp/pulpcore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.py
963 lines (805 loc) · 37.9 KB
/
handler.py
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
import asyncio
import logging
import os
import re
from gettext import gettext as _
from aiohttp.client_exceptions import ClientResponseError
from aiohttp.web import FileResponse, StreamResponse, HTTPOk
from aiohttp.web_exceptions import (
HTTPForbidden,
HTTPFound,
HTTPNotFound,
HTTPRequestRangeNotSatisfiable,
)
from yarl import URL
from asgiref.sync import sync_to_async
import django
from pulpcore.responses import ArtifactResponse
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pulpcore.app.settings")
django.setup()
from django.conf import settings # noqa: E402: module level not at top of file
from django.core.exceptions import ( # noqa: E402: module level not at top of file
MultipleObjectsReturned,
ObjectDoesNotExist,
)
from django.db import ( # noqa: E402: module level not at top of file
connection,
DatabaseError,
IntegrityError,
models,
transaction,
)
from pulpcore.app.models import ( # noqa: E402: module level not at top of file
Artifact,
ArtifactDistribution,
ContentArtifact,
Distribution,
Publication,
Remote,
RemoteArtifact,
)
from pulpcore.app import mime_types # noqa: E402: module level not at top of file
from pulpcore.exceptions import UnsupportedDigestValidationError # noqa: E402
from jinja2 import Template # noqa: E402: module level not at top of file
from pulpcore.cache import AsyncContentCache # noqa: E402
log = logging.getLogger(__name__)
class PathNotResolved(HTTPNotFound):
"""
The path could not be resolved to a published file.
This could be caused by either the distribution, the publication,
or the published file could not be found.
"""
def __init__(self, path, *args, **kwargs):
"""Initialize the Exception."""
self.path = path
super().__init__(*args, **kwargs)
class DistroListings(HTTPOk):
"""
Response for browsing through the distributions and their potential multi-layered base-paths.
This is returned when visiting the base path of the content app (/pulp/content/) or a partial
base path of a distribution, e.g. /pulp/content/foo/ for distros /foo/bar/ & /foo/baz/
"""
def __init__(self, path, distros):
"""Create the HTML response."""
distros = distros.exclude(pulp_type=ArtifactDistribution.get_pulp_type())
if settings.HIDE_GUARDED_DISTRIBUTIONS:
distros = distros.filter(content_guard__isnull=True)
base_paths = (
distros.annotate(rel_path=models.functions.Substr("base_path", 1 + len(path)))
.annotate(
path=models.Func(
models.F("rel_path"),
function="SUBSTRING",
template="%(function)s(%(expressions)s,'([^/]*)')",
)
)
.order_by("path")
.values_list("path", flat=True)
.distinct()
)
directory_list = (f"{b}/" for b in base_paths)
html = Handler.render_html(directory_list)
super().__init__(body=html, headers={"Content-Type": "text/html"})
class ArtifactNotFound(Exception):
"""
The artifact associated with a published-artifact does not exist.
"""
pass
class Handler:
"""
A default Handler for the Content App that also can be subclassed to create custom handlers.
This Handler will perform the following:
1. Match the request against a Distribution
2. Call the certguard check if a certguard exists for the matched Distribution.
3. If the Distribution has a `publication` serve that Publication's `PublishedArtifacts`,
`PublishedMetadata` by the remaining `relative path`. If still unserved and if `pass_through`
is set, the associated `repository_version` will have its `ContentArtifacts` served by
`relative_path` also. This will serve the associated `Artifact`.
4. If still unmatched, and the Distribution has a `repository` attribute set, find it's latest
`repository_version`. If the Distribution has a `repository_version` attribute set, use that.
For this `repository_version`, find matching `ContentArtifact` objects by `relative_path` and
serve them. If there is an associated `Artifact` return it.
5. If the Distribution has a `remote`, find an associated `RemoteArtifact` that matches by
`relative_path`. Fetch and stream the corresponding `RemoteArtifact` to the client,
optionally saving the `Artifact` depending on the `policy` attribute.
"""
hop_by_hop_headers = [
"connection",
"content-encoding",
"content-length",
"keep-alive",
"public",
"proxy-authenticate",
"transfer-encoding",
"upgrade",
]
distribution_model = None
@staticmethod
def _reset_db_connection():
"""
Reset database connection if it's unusable or obselete to avoid "connection already closed".
"""
connection.close_if_unusable_or_obsolete()
async def list_distributions(self, request):
"""
The handler for an HTML listing all distributions
Args:
request (:class:`aiohttp.web.request`): The request from the client.
Raises:
:class:`aiohttp.web.HTTPOk`: The response back to the client.
:class: `PathNotResolved`: 404 error response when path doesn't exist.
"""
def get_base_paths_blocking():
distro_model = self.distribution_model or Distribution
raise DistroListings(path="", distros=distro_model.objects.all())
if request.method.lower() == "head":
raise HTTPOk(headers={"Content-Type": "text/html"})
await sync_to_async(get_base_paths_blocking)()
@classmethod
async def find_base_path_cached(cls, request, cached):
"""
Finds the base-path to use for the base-key in the cache
Args:
request (:class:`aiohttp.web.request`): The request from the client.
cached (:class:`CacheAiohttp`): The Pulp cache
Returns:
str: The base-path associated with this request
"""
path = request.match_info["path"]
base_paths = cls._base_paths(path)
multiplied_base_paths = []
for i, base_path in enumerate(base_paths):
copied_by_index_base_path = [base_path for _ in range(i + 1)]
multiplied_base_paths.extend(copied_by_index_base_path)
index_p1 = await cached.exists(base_key=multiplied_base_paths)
if index_p1:
return base_paths[index_p1 - 1]
else:
distro = await sync_to_async(cls._match_distribution)(path)
return distro.base_path
@classmethod
async def auth_cached(cls, request, cached, base_key):
"""
Authentication check for the cached stream_content handler
Args:
request (:class:`aiohttp.web.request`): The request from the client.
cached (:class:`CacheAiohttp`): The Pulp cache
base_key (str): The base_key associated with this response
"""
guard_key = "DISTRO#GUARD#PRESENT"
present = await cached.get(guard_key, base_key=base_key)
if present == b"True" or present is None:
path = request.match_info["path"]
distro = await sync_to_async(cls._match_distribution)(path)
try:
guard = await sync_to_async(cls._permit)(request, distro)
except HTTPForbidden:
guard = True
raise
finally:
if not present:
await cached.set(guard_key, str(guard), base_key=base_key)
@AsyncContentCache(
base_key=lambda req, cac: Handler.find_base_path_cached(req, cac),
auth=lambda req, cac, bk: Handler.auth_cached(req, cac, bk),
)
async def stream_content(self, request):
"""
The request handler for the Content app.
Args:
request (:class:`aiohttp.web.request`): The request from the client.
Returns:
:class:`aiohttp.web.StreamResponse` or :class:`aiohttp.web.FileResponse`: The response
back to the client.
"""
path = request.match_info["path"]
return await self._match_and_stream(path, request)
@staticmethod
def _base_paths(path):
"""
Get a list of base paths used to match a distribution.
Args:
path (str): The path component of the URL.
Returns:
list: Of base paths.
"""
tree = []
while True:
base = os.path.split(path)[0]
if not base.lstrip("/"):
break
tree.append(base)
path = base
return tree
@classmethod
def _match_distribution(cls, path):
"""
Match a distribution using a list of base paths and return its detail object.
Args:
path (str): The path component of the URL.
Returns:
The detail object of the matched distribution.
Raises:
DistroListings: when multiple matches are possible.
PathNotResolved: when not matched.
"""
base_paths = cls._base_paths(path)
distro_model = cls.distribution_model or Distribution
try:
return (
distro_model.objects.select_related(
"repository", "repository_version", "publication", "remote"
)
.get(base_path__in=base_paths)
.cast()
)
except ObjectDoesNotExist:
if path.rstrip("/") in base_paths:
distros = distro_model.objects.filter(base_path__startswith=path)
if distros.count():
raise DistroListings(path=path, distros=distros)
log.debug(
_("Distribution not matched for {path} using: {base_paths}").format(
path=path, base_paths=base_paths
)
)
raise PathNotResolved(path)
@staticmethod
def _permit(request, distribution):
"""
Permit the request.
Authorization is delegated to the optional content-guard associated with the distribution.
Args:
request (:class:`aiohttp.web.Request`): A request for a published file.
distribution (detail of :class:`pulpcore.plugin.models.Distribution`): The matched
distribution.
Raises:
:class:`aiohttp.web_exceptions.HTTPForbidden`: When not permitted.
"""
guard = distribution.content_guard
if not guard:
return False
try:
guard.cast().permit(request)
except PermissionError as pe:
log.debug(
'Path: %(p)s not permitted by guard: "%(g)s" reason: %(r)s',
{"p": request.path, "g": guard.name, "r": str(pe)},
)
raise HTTPForbidden(reason=str(pe))
return True
@staticmethod
def response_headers(path):
"""
Get the Content-Type and Encoding-Type headers for the requested `path`.
Args:
path (str): The relative path that was requested.
Returns:
headers (dict): A dictionary of response headers.
"""
content_type = mime_types.get_type(path)
headers = {}
if content_type:
headers["Content-Type"] = content_type
return headers
@staticmethod
def render_html(directory_list):
"""
Render a list of strings as an HTML list of links.
Args:
directory_list (iterable): an iterable of strings representing file and directory names
Returns:
String representing HTML of the directory listing.
"""
template = Template(
"""
<!DOCTYPE html>
<html>
<body>
<ul>
{% for name in dir_list %}
<li><a href="{{ name|e }}">{{ name|e }}</a></li>
{% endfor %}
</ul>
</body>
</html>
"""
)
return template.render(dir_list=sorted(directory_list))
async def list_directory(self, repo_version, publication, path):
"""
Generate a set with directory listing of the path.
This method expects either a repo_version or a publication in addition to a path. This
method generates a set of strings representing the list of a path inside the repository
version or publication.
Args:
repo_version (:class:`~pulpcore.app.models.RepositoryVersion`): The repository version
publication (:class:`~pulpcore.app.models.Publication`): Publication
path (str): relative path inside the repo version of publication.
Returns:
Set of strings representing the files and directories in the directory listing.
"""
def file_or_directory_name(directory_path, relative_path):
result = re.match(r"({})([^\/]*)(\/*)".format(directory_path), relative_path)
return "{}{}".format(result.groups()[1], result.groups()[2])
def list_directory_blocking():
if not publication and not repo_version:
raise Exception("Either a repo_version or publication is required.")
if publication and repo_version:
raise Exception("Either a repo_version or publication can be specified.")
directory_list = set()
if publication:
pas = publication.published_artifact.filter(relative_path__startswith=path)
for pa in pas:
directory_list.add(file_or_directory_name(path, pa.relative_path))
if publication.pass_through:
cas = ContentArtifact.objects.filter(
content__in=publication.repository_version.content,
relative_path__startswith=path,
)
for ca in cas:
directory_list.add(file_or_directory_name(path, ca.relative_path))
if repo_version:
cas = ContentArtifact.objects.filter(
content__in=repo_version.content, relative_path__startswith=path
)
for ca in cas:
directory_list.add(file_or_directory_name(path, ca.relative_path))
if directory_list:
return directory_list
else:
raise PathNotResolved(path)
return await sync_to_async(list_directory_blocking)()
async def _match_and_stream(self, path, request):
"""
Match the path and stream results either from the filesystem or by downloading new data.
After deciding the client can access the distribution at ``path``, this function calls
:meth:`Distribution.content_handler`. If that function returns a not-None result, it is
returned to the client.
Then the publication linked to the Distribution is used to determine what content should
be served. If ``path`` is a directory entry (i.e. not a file), the directory contents
are served to the client. This method calls
:meth:`Distribution.content_handler_list_directory` to acquire any additional entries the
Distribution's content_handler might serve in that directory. If there is an Artifact to be
served, it is served to the client.
If there's no publication, the above paragraph is applied to the latest repository linked
to the matched Distribution.
Finally, when nothing is served to client yet, we check if there is a remote for the
Distribution. If so, the Artifact is pulled from the remote and streamed to the client.
Args:
path (str): The path component of the URL.
request(:class:`~aiohttp.web.Request`): The request to prepare a response for.
Raises:
PathNotResolved: The path could not be matched to a published file.
PermissionError: When not permitted.
Returns:
:class:`aiohttp.web.StreamResponse` or :class:`aiohttp.web.FileResponse`: The response
streamed back to the client.
"""
distro = await sync_to_async(self._match_distribution)(path)
await sync_to_async(self._permit)(request, distro)
rel_path = path.lstrip("/")
rel_path = rel_path[len(distro.base_path) :]
rel_path = rel_path.lstrip("/")
content_handler_result = await sync_to_async(distro.content_handler)(rel_path)
if content_handler_result is not None:
return content_handler_result
headers = self.response_headers(rel_path)
repository = distro.repository
publication = distro.publication
repo_version = distro.repository_version
if repository:
def get_latest_publication_or_version_blocking():
nonlocal repo_version
nonlocal publication
# Search for publication serving the closest latest version
if not publication:
try:
versions = repository.versions.all()
publications = Publication.objects.filter(
repository_version__in=versions, complete=True
)
publication = publications.select_related("repository_version").latest(
"repository_version", "pulp_created"
)
repo_version = publication.repository_version
except ObjectDoesNotExist:
pass
if not repo_version:
repo_version = repository.latest_version()
await sync_to_async(get_latest_publication_or_version_blocking)()
if publication:
if rel_path == "" or rel_path[-1] == "/":
try:
index_path = "{}index.html".format(rel_path)
await sync_to_async(publication.published_artifact.get)(
relative_path=index_path
)
rel_path = index_path
headers = self.response_headers(rel_path)
except ObjectDoesNotExist:
dir_list = await self.list_directory(None, publication, rel_path)
dir_list.update(
await sync_to_async(distro.content_handler_list_directory)(rel_path)
)
return HTTPOk(
headers={"Content-Type": "text/html"}, body=self.render_html(dir_list)
)
# published artifact
try:
def get_contentartifact_blocking():
return (
publication.published_artifact.select_related(
"content_artifact",
"content_artifact__artifact",
)
.get(relative_path=rel_path)
.content_artifact
)
ca = await sync_to_async(get_contentartifact_blocking)()
except ObjectDoesNotExist:
pass
else:
if ca.artifact:
return await self._serve_content_artifact(ca, headers, request)
else:
return await self._stream_content_artifact(
request, StreamResponse(headers=headers), ca
)
# pass-through
if publication.pass_through:
try:
def get_contentartifact_blocking():
ca = ContentArtifact.objects.select_related("artifact").get(
content__in=publication.repository_version.content,
relative_path=rel_path,
)
return ca
ca = await sync_to_async(get_contentartifact_blocking)()
except MultipleObjectsReturned:
log.error(
"Multiple (pass-through) matches for {b}/{p}",
{"b": distro.base_path, "p": rel_path},
)
raise
except ObjectDoesNotExist:
pass
else:
if ca.artifact:
return await self._serve_content_artifact(ca, headers, request)
else:
return await self._stream_content_artifact(
request, StreamResponse(headers=headers), ca
)
if repo_version and not publication and not distro.SERVE_FROM_PUBLICATION:
if rel_path == "" or rel_path[-1] == "/":
index_path = "{}index.html".format(rel_path)
def contentartifact_exists_blocking():
return ContentArtifact.objects.filter(
content__in=repo_version.content, relative_path=index_path
).exists()
contentartifact_exists = await sync_to_async(contentartifact_exists_blocking)()
if contentartifact_exists:
rel_path = index_path
else:
dir_list = await self.list_directory(repo_version, None, rel_path)
dir_list.update(
await sync_to_async(distro.content_handler_list_directory)(rel_path)
)
return HTTPOk(
headers={"Content-Type": "text/html"}, body=self.render_html(dir_list)
)
try:
def get_contentartifact_blocking():
ca = ContentArtifact.objects.select_related("artifact").get(
content__in=repo_version.content, relative_path=rel_path
)
return ca
ca = await sync_to_async(get_contentartifact_blocking)()
except MultipleObjectsReturned:
log.error(
"Multiple (pass-through) matches for {b}/{p}",
{"b": distro.base_path, "p": rel_path},
)
raise
except ObjectDoesNotExist:
pass
else:
if ca.artifact:
return await self._serve_content_artifact(ca, headers, request)
else:
return await self._stream_content_artifact(
request, StreamResponse(headers=headers), ca
)
if distro.remote:
def cast_remote_blocking():
return distro.remote.cast()
remote = await sync_to_async(cast_remote_blocking)()
try:
url = remote.get_remote_artifact_url(rel_path, request=request)
def get_remote_artifact_blocking():
ra = RemoteArtifact.objects.select_related(
"content_artifact",
"content_artifact__artifact",
"remote",
).get(remote=remote, url=url)
return ra
ra = await sync_to_async(get_remote_artifact_blocking)()
ca = ra.content_artifact
if ca.artifact:
return await self._serve_content_artifact(ca, headers, request)
else:
return await self._stream_content_artifact(
request, StreamResponse(headers=headers), ca
)
except ObjectDoesNotExist:
ca = ContentArtifact(relative_path=rel_path)
ra = RemoteArtifact(remote=remote, url=url, content_artifact=ca)
return await self._stream_remote_artifact(
request, StreamResponse(headers=headers), ra
)
if not any([repository, repo_version, publication, distro.remote]):
reason = _(
"Distribution is not pointing to a publication, repository, repository version,"
" or remote."
)
else:
reason = None
raise PathNotResolved(path, reason=reason)
async def _stream_content_artifact(self, request, response, content_artifact):
"""
Stream and optionally save a ContentArtifact by requesting it using the associated remote.
If a fatal download failure occurs while downloading and there are additional
:class:`~pulpcore.plugin.models.RemoteArtifact` objects associated with the
:class:`~pulpcore.plugin.models.ContentArtifact` they will also be tried. If all
:class:`~pulpcore.plugin.models.RemoteArtifact` downloads raise exceptions, an HTTP 502
error is returned to the client.
Args:
request(:class:`~aiohttp.web.Request`): The request to prepare a response for.
response (:class:`~aiohttp.web.StreamResponse`): The response to stream data to.
content_artifact (:class:`~pulpcore.plugin.models.ContentArtifact`): The ContentArtifact
to fetch and then stream back to the client
Raises:
:class:`~aiohttp.web.HTTPNotFound` when no
:class:`~pulpcore.plugin.models.RemoteArtifact` objects associated with the
:class:`~pulpcore.plugin.models.ContentArtifact` returned the binary data needed for
the client.
"""
def get_remote_artifacts_blocking():
return list(content_artifact.remoteartifact_set.select_related("remote").order_by_acs())
remote_artifacts = await sync_to_async(get_remote_artifacts_blocking)()
for remote_artifact in remote_artifacts:
try:
response = await self._stream_remote_artifact(request, response, remote_artifact)
return response
except (ClientResponseError, UnsupportedDigestValidationError) as e:
log.warning(
"Could not download remote artifact at '{}': {}".format(
remote_artifact.url, str(e)
)
)
continue
raise HTTPNotFound()
def _save_artifact(self, download_result, remote_artifact):
"""
Create/Get an Artifact and associate it to a RemoteArtifact and/or ContentArtifact.
Create (or get if already existing) an :class:`~pulpcore.plugin.models.Artifact`
based on the `download_result` and associate it to the `content_artifact` of the given
`remote_artifact`. Both the created artifact and the updated content_artifact are saved to
the DB. The `remote_artifact` is also saved for the pull-through caching use case.
Plugin-writers may overide this method if their content module requires
additional/different steps for saving.
Args:
download_result (:class:`~pulpcore.plugin.download.DownloadResult`: The
DownloadResult for the downloaded artifact.
remote_artifact (:class:`~pulpcore.plugin.models.RemoteArtifact`): The
RemoteArtifact to associate the Artifact with.
Returns:
The associated :class:`~pulpcore.plugin.models.Artifact`.
"""
content_artifact = remote_artifact.content_artifact
remote = remote_artifact.remote
artifact = Artifact(**download_result.artifact_attributes, file=download_result.path)
with transaction.atomic():
try:
with transaction.atomic():
artifact.save()
except IntegrityError:
try:
artifact = Artifact.objects.get(artifact.q())
artifact.touch()
except (Artifact.DoesNotExist, DatabaseError):
# it's possible that orphan cleanup deleted the artifact
# so fall back to creating a new artifact again
artifact = Artifact(
**download_result.artifact_attributes, file=download_result.path
)
artifact.save()
else:
# The file needs to be unlinked because it was not used to create an artifact.
# The artifact must have already been saved while servicing another request for
# the same artifact.
os.unlink(download_result.path)
update_content_artifact = True
if content_artifact._state.adding:
# This is the first time pull-through content was requested.
rel_path = content_artifact.relative_path
c_type = remote.get_remote_artifact_content_type(rel_path)
content = c_type.init_from_artifact_and_relative_path(artifact, rel_path)
try:
with transaction.atomic():
content.save()
content_artifact.content = content
content_artifact.save()
except IntegrityError:
# There is already content for this Artifact
content = c_type.objects.get(content.q())
artifacts = content._artifacts
if artifact.sha256 != artifacts[0].sha256:
raise RuntimeError(
"The Artifact downloaded during pull-through does not "
"match the Artifact already stored for the same "
"content."
)
content_artifact = ContentArtifact.objects.get(content=content)
update_content_artifact = False
try:
with transaction.atomic():
remote_artifact.content_artifact = content_artifact
remote_artifact.save()
except IntegrityError:
# Remote artifact must have already gotten saved during a parallel request
log.info("RemoteArtifact already exists.")
if update_content_artifact:
content_artifact.artifact = artifact
content_artifact.save()
return artifact
async def _serve_content_artifact(self, content_artifact, headers, request):
"""
Handle response for a Content Artifact with the file present.
Depending on where the file storage (e.g. filesystem, S3, etc) this could be responding with
the file (filesystem) or a redirect (S3).
Args:
content_artifact (:class:`pulpcore.app.models.ContentArtifact`): The Content Artifact to
respond with.
headers (dict): A dictionary of response headers.
request(:class:`~aiohttp.web.Request`): The request to prepare a response for.
Raises:
:class:`aiohttp.web_exceptions.HTTPFound`: When we need to redirect to the file
NotImplementedError: If file is stored in a file storage we can't handle
Returns:
The :class:`aiohttp.web.FileResponse` for the file.
"""
artifact_file = content_artifact.artifact.file
artifact_name = artifact_file.name
filename = os.path.basename(content_artifact.relative_path)
content_disposition = f"attachment;filename={filename}"
if settings.DEFAULT_FILE_STORAGE == "pulpcore.app.models.storage.FileSystem":
path = os.path.join(settings.MEDIA_ROOT, artifact_name)
if not os.path.exists(path):
raise Exception(_("Expected path '{}' is not found").format(path))
return FileResponse(path, headers=headers)
elif not settings.REDIRECT_TO_OBJECT_STORAGE:
return ArtifactResponse(content_artifact.artifact, headers=headers)
elif settings.DEFAULT_FILE_STORAGE == "storages.backends.s3boto3.S3Boto3Storage":
parameters = {"ResponseContentDisposition": content_disposition}
if headers.get("Content-Type"):
parameters["ResponseContentType"] = headers.get("Content-Type")
url = URL(
artifact_file.storage.url(
artifact_name, parameters=parameters, http_method=request.method
),
encoded=True,
)
raise HTTPFound(url)
elif settings.DEFAULT_FILE_STORAGE == "storages.backends.azure_storage.AzureStorage":
parameters = {"content_disposition": content_disposition}
if headers.get("Content-Type"):
parameters["content_type"] = headers.get("Content-Type")
url = URL(artifact_file.storage.url(artifact_name, parameters=parameters), encoded=True)
raise HTTPFound(url)
elif settings.DEFAULT_FILE_STORAGE == "storages.backends.gcloud.GoogleCloudStorage":
parameters = {"response_disposition": content_disposition}
if headers.get("Content-Type"):
parameters["content_type"] = headers.get("Content-Type")
url = URL(artifact_file.storage.url(artifact_name, parameters=parameters), encoded=True)
raise HTTPFound(url)
else:
raise NotImplementedError()
async def _stream_remote_artifact(self, request, response, remote_artifact):
"""
Stream and save a RemoteArtifact.
Args:
request(:class:`~aiohttp.web.Request`): The request to prepare a response for.
response (:class:`~aiohttp.web.StreamResponse`): The response to stream data to.
remote_artifact (:class:`~pulpcore.plugin.models.RemoteArtifact`): The RemoteArtifact
to fetch and then stream back to the client
Raises:
:class:`~aiohttp.web.HTTPNotFound` when no
:class:`~pulpcore.plugin.models.RemoteArtifact` objects associated with the
:class:`~pulpcore.plugin.models.ContentArtifact` returned the binary data needed for
the client.
"""
remote = await sync_to_async(remote_artifact.remote.cast)()
log.debug(
"Streaming content for {url} from Remote {remote}-{source}".format(
url=request.match_info["path"], remote=remote.name, source=remote_artifact.url
)
)
# According to RFC7233 if a server cannot satisfy a Range request, the response needs to
# contain a Content-Range header with an unsatisfied-range value.
try:
range_start, range_stop = request.http_range.start, request.http_range.stop
size = remote_artifact.size
if size and range_start and range_start >= size:
raise HTTPRequestRangeNotSatisfiable(headers={"Content-Range": f"bytes */{size}"})
except ValueError:
size = remote_artifact.size or "*"
raise HTTPRequestRangeNotSatisfiable(headers={"Content-Range": f"bytes */{size}"})
actual_content_length = None
if range_start or range_stop:
response.set_status(206)
if range_stop and size and range_stop > size:
start = 0 if range_start is None else range_start
actual_content_length = size - start
async def handle_response_headers(headers):
for name, value in headers.items():
lower_name = name.lower()
if lower_name not in self.hop_by_hop_headers:
response.headers[name] = value
elif response.status == 206 and lower_name == "content-length":
content_length = int(value)
start = 0 if range_start is None else range_start
if range_stop is None:
stop = content_length
elif actual_content_length:
stop = start + actual_content_length
else:
stop = range_stop
range_bytes = stop - start
if actual_content_length:
response.headers[name] = str(actual_content_length)
else:
response.headers[name] = str(range_bytes)
# aiohttp adds a 1 to the range.stop compared to http headers (including) to
# match python array adressing (exclusive)
response.headers["Content-Range"] = "bytes {0}-{1}/{2}".format(
start, stop - 1, content_length
)
await response.prepare(request)
data_size_handled = 0
async def handle_data(data):
nonlocal data_size_handled
if range_start or range_stop:
start_byte_pos = 0
end_byte_pos = len(data)
if range_start:
start_byte_pos = max(0, range_start - data_size_handled)
if range_stop:
end_byte_pos = min(len(data), range_stop - data_size_handled)
data_for_client = data[start_byte_pos:end_byte_pos]
await response.write(data_for_client)
data_size_handled = data_size_handled + len(data)
else:
await response.write(data)
if remote.policy != Remote.STREAMED:
await original_handle_data(data)
async def finalize():
if remote.policy != Remote.STREAMED:
await original_finalize()
downloader = remote.get_downloader(
remote_artifact=remote_artifact, headers_ready_callback=handle_response_headers
)
original_handle_data = downloader.handle_data
downloader.handle_data = handle_data
original_finalize = downloader.finalize
downloader.finalize = finalize
download_result = await downloader.run()
if remote.policy != Remote.STREAMED:
await asyncio.shield(
sync_to_async(self._save_artifact)(download_result, remote_artifact)
)
await response.write_eof()
if response.status == 404:
raise HTTPNotFound()
return response