-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy paths3.py
More file actions
1854 lines (1636 loc) · 69.2 KB
/
s3.py
File metadata and controls
1854 lines (1636 loc) · 69.2 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
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import errno
import json
import os
import re
import sys
import time
import shutil
import random
import subprocess
from io import RawIOBase, BufferedIOBase
from itertools import chain, starmap
from tempfile import mkdtemp, NamedTemporaryFile
from typing import Dict, Iterable, List, Optional, Tuple, Union, TYPE_CHECKING
from metaflow import FlowSpec
from metaflow.metaflow_current import current
from metaflow.metaflow_config import (
DATATOOLS_S3ROOT,
S3_DIRECT_BOTO3,
S3_RETRY_COUNT,
S3_TRANSIENT_RETRY_COUNT,
S3_LOG_TRANSIENT_RETRIES,
S3_SERVER_SIDE_ENCRYPTION,
S3_WORKER_COUNT,
TEMPDIR,
)
from metaflow.util import (
is_stringish,
to_bytes,
to_unicode,
to_fileobj,
url_quote,
url_unquote,
)
from metaflow.tuple_util import namedtuple_with_defaults
from metaflow.exception import MetaflowException
from metaflow.debug import debug
import metaflow.tracing as tracing
try:
# python2
from urlparse import urlparse
except:
# python3
from urllib.parse import urlparse
from .s3util import (
get_s3_client,
read_in_chunks,
get_timestamp,
TRANSIENT_RETRY_START_LINE,
TRANSIENT_RETRY_LINE_CONTENT,
)
if TYPE_CHECKING:
import metaflow
def _check_and_init_s3_deps():
try:
import boto3
from boto3.s3.transfer import TransferConfig
except (ImportError, ModuleNotFoundError):
raise MetaflowException("You need to install 'boto3' in order to use S3.")
def check_s3_deps(func):
"""The decorated function checks S3 dependencies (as needed for AWS S3 storage backend).
This includes boto3.
"""
def _inner_func(*args, **kwargs):
_check_and_init_s3_deps()
return func(*args, **kwargs)
return _inner_func
TEST_INJECT_RETRYABLE_FAILURES = int(
os.environ.get("METAFLOW_S3_TEST_RETRYABLE_FAILURES", 0)
)
def ensure_unicode(x):
return None if x is None else to_unicode(x)
PutValue = Union[RawIOBase, BufferedIOBase, str, bytes]
S3GetObject = namedtuple_with_defaults(
"S3GetObject", [("key", str), ("offset", int), ("length", int)]
)
S3GetObject.__module__ = __name__
S3PutObject = namedtuple_with_defaults(
"S3PutObject",
[
("key", str),
("value", Optional[PutValue]),
("path", Optional[str]),
("content_type", Optional[str]),
("encryption", Optional[str]),
("metadata", Optional[Dict[str, str]]),
],
defaults=(None, None, None, None, None),
)
S3PutObject.__module__ = __name__
RangeInfo = namedtuple_with_defaults(
"RangeInfo",
[("total_size", int), ("request_offset", int), ("request_length", int)],
defaults=(0, -1),
)
RangeInfo.__module__ = __name__
RANGE_MATCH = re.compile(r"bytes (?P<start>[0-9]+)-(?P<end>[0-9]+)/(?P<total>[0-9]+)")
class MetaflowS3InvalidObject(MetaflowException):
headline = "Not a string-like object"
class MetaflowS3URLException(MetaflowException):
headline = "Invalid address"
class MetaflowS3Exception(MetaflowException):
headline = "S3 access failed"
class MetaflowS3NotFound(MetaflowException):
headline = "S3 object not found"
class MetaflowS3AccessDenied(MetaflowException):
headline = "S3 access denied"
class MetaflowS3InvalidRange(MetaflowException):
headline = "S3 invalid range"
class MetaflowS3InsufficientDiskSpace(MetaflowException):
headline = "Insufficient disk space"
class S3Object(object):
"""
This object represents a path or an object in S3,
with an optional local copy.
`S3Object`s are not instantiated directly, but they are returned
by many methods of the `S3` client.
"""
def __init__(
self,
prefix: str,
url: str,
path: str,
size: Optional[int] = None,
content_type: Optional[str] = None,
metadata: Optional[Dict[str, str]] = None,
range_info: Optional[RangeInfo] = None,
last_modified: Optional[int] = None,
encryption: Optional[str] = None,
):
# all fields of S3Object should return a unicode object
prefix, url, path = map(ensure_unicode, (prefix, url, path))
self._size = size
self._url = url
self._path = path
self._key = None
self._content_type = content_type
self._last_modified = last_modified
self._metadata = None
if metadata is not None and "metaflow-user-attributes" in metadata:
self._metadata = json.loads(metadata["metaflow-user-attributes"])
if range_info and (
range_info.request_length is None or range_info.request_length < 0
):
self._range_info = RangeInfo(
range_info.total_size, range_info.request_offset, range_info.total_size
)
else:
self._range_info = range_info
if path:
self._size = os.stat(self._path).st_size
if prefix is None or prefix == url:
self._key = url
self._prefix = None
else:
self._key = url[len(prefix.rstrip("/")) + 1 :].rstrip("/")
self._prefix = prefix
self._encryption = encryption
@property
def exists(self) -> bool:
"""
Does this key correspond to an object in S3?
Returns
-------
bool
True if this object points at an existing object (file) in S3.
"""
return self._size is not None
@property
def downloaded(self) -> bool:
"""
Has this object been downloaded?
If True, the contents can be accessed through `path`, `blob`,
and `text` properties.
Returns
-------
bool
True if the contents of this object have been downloaded.
"""
return bool(self._path)
@property
def url(self) -> str:
"""
S3 location of the object
Returns
-------
str
The S3 location of this object.
"""
return self._url
@property
def prefix(self) -> str:
"""
Prefix requested that matches this object.
Returns
-------
str
Requested prefix
"""
return self._prefix
@property
def key(self) -> str:
"""
Key corresponds to the key given to the get call that produced
this object.
This may be a full S3 URL or a suffix based on what
was requested.
Returns
-------
str
Key requested.
"""
return self._key
@property
def path(self) -> Optional[str]:
"""
Path to a local temporary file corresponding to the object downloaded.
This file gets deleted automatically when a S3 scope exits.
Returns None if this S3Object has not been downloaded.
Returns
-------
str
Local path, if the object has been downloaded.
"""
return self._path
@property
def blob(self) -> Optional[bytes]:
"""
Contents of the object as a byte string or None if the
object hasn't been downloaded.
Returns
-------
bytes
Contents of the object as bytes.
"""
if self._path:
with open(self._path, "rb") as f:
return f.read()
@property
def text(self) -> Optional[str]:
"""
Contents of the object as a string or None if the
object hasn't been downloaded.
The object is assumed to contain UTF-8 encoded data.
Returns
-------
str
Contents of the object as text.
"""
if self._path:
return self.blob.decode("utf-8", errors="replace")
@property
def size(self) -> Optional[int]:
"""
Size of the object in bytes.
Returns None if the key does not correspond to an object in S3.
Returns
-------
int
Size of the object in bytes, if the object exists.
"""
return self._size
@property
def has_info(self) -> bool:
"""
Returns true if this `S3Object` contains the content-type MIME header or
user-defined metadata.
If False, this means that `content_type`, `metadata`, `range_info` and
`last_modified` will return None.
Returns
-------
bool
True if additional metadata is available.
"""
return (
self._content_type is not None
or self._metadata is not None
or self._range_info is not None
or self._encryption is not None
)
@property
def metadata(self) -> Optional[Dict[str, str]]:
"""
Returns a dictionary of user-defined metadata, or None if no metadata
is defined.
Returns
-------
Dict
User-defined metadata.
"""
return self._metadata
@property
def content_type(self) -> Optional[str]:
"""
Returns the content-type of the S3 object or None if it is not defined.
Returns
-------
str
Content type or None if the content type is undefined.
"""
return self._content_type
@property
def encryption(self) -> Optional[str]:
"""
Returns the encryption type of the S3 object or None if it is not defined.
Returns
-------
str
Server-side-encryption type or None if parameter is not set.
"""
return self._encryption
@property
def range_info(self) -> Optional[RangeInfo]:
"""
If the object corresponds to a partially downloaded object, returns
information of what was downloaded.
The returned object has the following fields:
- `total_size`: Size of the object in S3.
- `request_offset`: The starting offset.
- `request_length`: The number of bytes downloaded.
Returns
-------
namedtuple
An object containing information about the partial download. If
the `S3Object` doesn't correspond to a partially downloaded file,
returns None.
"""
return self._range_info
@property
def last_modified(self) -> Optional[int]:
"""
Returns the last modified unix timestamp of the object.
Returns
-------
int
Unix timestamp corresponding to the last modified time.
"""
return self._last_modified
def __str__(self):
if self._path:
return "<S3Object %s (%d bytes, local)>" % (self._url, self._size)
elif self._size:
return "<S3Object %s (%d bytes, in S3)>" % (self._url, self._size)
else:
return "<S3Object %s (object does not exist)>" % self._url
def __repr__(self):
return str(self)
class S3Client(object):
def __init__(self, s3_role_arn=None, s3_session_vars=None, s3_client_params=None):
self._s3_client = None
self._s3_error = None
self._s3_role = s3_role_arn
self._s3_session_vars = s3_session_vars
self._s3_client_params = s3_client_params
@property
def client(self):
if self._s3_client is None:
self.reset_client()
return self._s3_client
@property
def error(self):
if self._s3_error is None:
self.reset_client()
return self._s3_error
def reset_client(self):
self._s3_client, self._s3_error = get_s3_client(
s3_role_arn=self._s3_role,
s3_session_vars=self._s3_session_vars,
s3_client_params=self._s3_client_params,
)
class S3(object):
"""
The Metaflow S3 client.
This object manages the connection to S3 and a temporary diretory that is used
to download objects. Note that in most cases when the data fits in memory, no local
disk IO is needed as operations are cached by the operating system, which makes
operations fast as long as there is enough memory available.
The easiest way is to use this object as a context manager:
```
with S3() as s3:
data = [obj.blob for obj in s3.get_many(urls)]
print(data)
```
The context manager takes care of creating and deleting a temporary directory
automatically. Without a context manager, you must call `.close()` to delete
the directory explicitly:
```
s3 = S3()
data = [obj.blob for obj in s3.get_many(urls)]
s3.close()
```
You can customize the location of the temporary directory with `tmproot`. It
defaults to the current working directory.
To make it easier to deal with object locations, the client can be initialized
with an S3 path prefix. There are three ways to handle locations:
1. Use a `metaflow.Run` object or `self`, e.g. `S3(run=self)` which
initializes the prefix with the global `DATATOOLS_S3ROOT` path, combined
with the current run ID. This mode makes it easy to version data based
on the run ID consistently. You can use the `bucket` and `prefix` to
override parts of `DATATOOLS_S3ROOT`.
2. Specify an S3 prefix explicitly with `s3root`,
e.g. `S3(s3root='s3://mybucket/some/path')`.
3. Specify nothing, i.e. `S3()`, in which case all operations require
a full S3 url prefixed with `s3://`.
Parameters
----------
tmproot : str, default '.'
Where to store the temporary directory.
bucket : str, optional, default None
Override the bucket from `DATATOOLS_S3ROOT` when `run` is specified.
prefix : str, optional, default None
Override the path from `DATATOOLS_S3ROOT` when `run` is specified.
run : FlowSpec or Run, optional, default None
Derive path prefix from the current or a past run ID, e.g. S3(run=self).
s3root : str, optional, default None
If `run` is not specified, use this as the S3 prefix.
encryption : str, optional, default None
Server-side encryption to use when uploading objects to S3.
"""
TYPE = "s3"
@classmethod
def get_root_from_config(cls, echo, create_on_absent=True):
return DATATOOLS_S3ROOT
@check_s3_deps
def __init__(
self,
tmproot: str = TEMPDIR,
bucket: Optional[str] = None,
prefix: Optional[str] = None,
run: Optional[Union[FlowSpec, "metaflow.Run"]] = None,
s3root: Optional[str] = None,
encryption: Optional[str] = S3_SERVER_SIDE_ENCRYPTION,
**kwargs
):
if run:
# 1. use a (current) run ID with optional customizations
if DATATOOLS_S3ROOT is None:
raise MetaflowS3URLException(
"DATATOOLS_S3ROOT is not configured when trying to use S3 storage"
)
parsed = urlparse(DATATOOLS_S3ROOT)
if not bucket:
bucket = parsed.netloc
if not prefix:
prefix = parsed.path
if isinstance(run, FlowSpec):
if current.is_running_flow:
prefix = os.path.join(prefix, current.flow_name, current.run_id)
else:
raise MetaflowS3URLException(
"Initializing S3 with a FlowSpec outside of a running "
"flow is not supported."
)
else:
prefix = os.path.join(prefix, run.parent.id, run.id)
self._s3root = "s3://%s" % os.path.join(bucket, prefix.strip("/"))
elif s3root:
# 2. use an explicit S3 prefix
parsed = urlparse(to_unicode(s3root))
if parsed.scheme != "s3":
raise MetaflowS3URLException(
"s3root needs to be an S3 URL prefixed with s3://."
)
self._s3root = s3root.rstrip("/")
else:
# 3. use the client only with full URLs
self._s3root = None
# Note that providing a role, session vars or client params and a client
# will result in the role/session vars/client params being ignored
self._s3_role = kwargs.get("role", None)
self._s3_session_vars = kwargs.get("session_vars", None)
self._s3_client_params = kwargs.get("client_params", None)
self._s3_client = kwargs.get(
"external_client",
S3Client(
s3_role_arn=self._s3_role,
s3_session_vars=self._s3_session_vars,
s3_client_params=self._s3_client_params,
),
)
self._s3_inject_failures = kwargs.get(
"inject_failure_rate", TEST_INJECT_RETRYABLE_FAILURES
)
# Storing tmproot, bucket, ... as members to allow easier reconstruction
# during JSON deserialization
self._tmproot = tmproot
self._bucket = bucket
self._prefix = prefix
self._run = run
self._tmpdir = mkdtemp(dir=self._tmproot, prefix="metaflow.s3.")
self._encryption = encryption
def __enter__(self) -> "S3":
return self
def __exit__(self, *args):
self.close()
def close(self):
"""
Delete all temporary files downloaded in this context.
"""
try:
if not debug.s3client:
if self._tmpdir:
shutil.rmtree(self._tmpdir)
self._tmpdir = None
except:
pass
def _url(self, key_value):
# NOTE: All URLs are handled as Unicode objects (unicode in py2,
# string in py3) internally. We expect that all URLs passed to this
# class as either Unicode or UTF-8 encoded byte strings. All URLs
# returned are Unicode.
key = getattr(key_value, "key", key_value)
if self._s3root is None:
# NOTE: S3 allows fragments as part of object names, e.g. /dataset #1/data.txt
# Without allow_fragments=False the parsed.path for an object name with fragments is incomplete.
parsed = urlparse(to_unicode(key), allow_fragments=False)
if parsed.scheme == "s3" and parsed.path:
return key
else:
if current.is_running_flow:
raise MetaflowS3URLException(
"Specify S3(run=self) when you use S3 inside a running "
"flow. Otherwise you have to use S3 with full "
"s3:// urls."
)
else:
raise MetaflowS3URLException(
"Initialize S3 with an 's3root' or 'run' if you don't "
"want to specify full s3:// urls."
)
elif key:
if key.startswith("s3://"):
raise MetaflowS3URLException(
"Don't use absolute S3 URLs when the S3 client is "
"initialized with a prefix. URL: %s" % key
)
# Strip leading slashes to ensure os.path.join works correctly
# os.path.join discards the first argument if the second starts with '/'
return os.path.join(self._s3root, key.lstrip("/"))
else:
return self._s3root
def _url_and_range(self, key_value):
url = self._url(key_value)
start = getattr(key_value, "offset", None)
length = getattr(key_value, "length", None)
range_str = None
# Range specification are inclusive so getting from offset 500 for 100
# bytes will read as bytes=500-599
if start is not None or length is not None:
if start is None:
start = 0
if length is None:
# Fetch from offset till the end of the file
range_str = "bytes=%d-" % start
elif length < 0:
# Fetch from end; ignore start value here
range_str = "bytes=-%d" % (-length)
else:
# Typical range fetch
range_str = "bytes=%d-%d" % (start, start + length - 1)
return url, range_str
def list_paths(self, keys: Optional[Iterable[str]] = None) -> List[S3Object]:
"""
List the next level of paths in S3.
If multiple keys are specified, listings are done in parallel. The returned
S3Objects have `.exists == False` if the path refers to a prefix, not an
existing S3 object.
For instance, if the directory hierarchy is
```
a/0.txt
a/b/1.txt
a/c/2.txt
a/d/e/3.txt
f/4.txt
```
The `list_paths(['a', 'f'])` call returns
```
a/0.txt (exists == True)
a/b/ (exists == False)
a/c/ (exists == False)
a/d/ (exists == False)
f/4.txt (exists == True)
```
Parameters
----------
keys : Iterable[str], optional, default None
List of paths.
Returns
-------
List[S3Object]
S3Objects under the given paths, including prefixes (directories) that
do not correspond to leaf objects.
"""
def _list(keys):
if keys is None:
keys = [None]
urls = ((self._url(key).rstrip("/") + "/", None) for key in keys)
res = self._read_many_files("list", urls)
for s3prefix, s3url, size in res:
if size:
yield s3prefix, s3url, None, int(size)
else:
yield s3prefix, s3url, None, None
return list(starmap(S3Object, _list(keys)))
def list_recursive(self, keys: Optional[Iterable[str]] = None) -> List[S3Object]:
"""
List all objects recursively under the given prefixes.
If multiple keys are specified, listings are done in parallel. All objects
returned have `.exists == True` as this call always returns leaf objects.
For instance, if the directory hierarchy is
```
a/0.txt
a/b/1.txt
a/c/2.txt
a/d/e/3.txt
f/4.txt
```
The `list_paths(['a', 'f'])` call returns
```
a/0.txt (exists == True)
a/b/1.txt (exists == True)
a/c/2.txt (exists == True)
a/d/e/3.txt (exists == True)
f/4.txt (exists == True)
```
Parameters
----------
keys : Iterable[str], optional, default None
List of paths.
Returns
-------
List[S3Object]
S3Objects under the given paths.
"""
def _list(keys):
if keys is None:
keys = [None]
res = self._read_many_files(
"list", map(self._url_and_range, keys), recursive=True
)
for s3prefix, s3url, size in res:
yield s3prefix, s3url, None, int(size)
return list(starmap(S3Object, _list(keys)))
def info(self, key: Optional[str] = None, return_missing: bool = False) -> S3Object:
"""
Get metadata about a single object in S3.
This call makes a single `HEAD` request to S3 which can be
much faster than downloading all data with `get`.
Parameters
----------
key : str, optional, default None
Object to query. It can be an S3 url or a path suffix.
return_missing : bool, default False
If set to True, do not raise an exception for a missing key but
return it as an `S3Object` with `.exists == False`.
Returns
-------
S3Object
An S3Object corresponding to the object requested. The object
will have `.downloaded == False`.
"""
url = self._url(key)
# NOTE: S3 allows fragments as part of object names, e.g. /dataset #1/data.txt
# Without allow_fragments=False the parsed src.path for an object name with fragments is incomplete.
src = urlparse(url, allow_fragments=False)
def _info(s3, tmp):
resp = s3.head_object(Bucket=src.netloc, Key=src.path.lstrip('/"'))
return {
"content_type": resp.get("ContentType"),
"metadata": resp.get("Metadata", {}),
"size": resp["ContentLength"],
"last_modified": get_timestamp(resp["LastModified"]),
"encryption": resp.get("ServerSideEncryption"),
}
info_results = None
try:
_, info_results = self._one_boto_op(_info, url, create_tmp_file=False)
except MetaflowS3NotFound:
if return_missing:
info_results = None
else:
raise
if info_results:
return S3Object(
self._s3root,
url,
path=None,
size=info_results["size"],
content_type=info_results["content_type"],
metadata=info_results["metadata"],
last_modified=info_results["last_modified"],
encryption=info_results["encryption"],
)
return S3Object(self._s3root, url, None)
def info_many(
self, keys: Iterable[str], return_missing: bool = False
) -> List[S3Object]:
"""
Get metadata about many objects in S3 in parallel.
This call makes a single `HEAD` request to S3 which can be
much faster than downloading all data with `get`.
Parameters
----------
keys : Iterable[str]
Objects to query. Each key can be an S3 url or a path suffix.
return_missing : bool, default False
If set to True, do not raise an exception for a missing key but
return it as an `S3Object` with `.exists == False`.
Returns
-------
List[S3Object]
A list of S3Objects corresponding to the paths requested. The
objects will have `.downloaded == False`.
"""
def _head():
from . import s3op
res = self._read_many_files(
"info", map(self._url_and_range, keys), verbose=False, listing=True
)
for s3prefix, s3url, fname in res:
if fname:
# We have a metadata file to read from
with open(os.path.join(self._tmpdir, fname), "r") as f:
info = json.load(f)
if info["error"] is not None:
# We have an error, we check if it is a missing file
if info["error"] == s3op.ERROR_URL_NOT_FOUND:
if return_missing:
yield self._s3root, s3url, None
else:
raise MetaflowS3NotFound()
elif info["error"] == s3op.ERROR_URL_ACCESS_DENIED:
raise MetaflowS3AccessDenied()
else:
raise MetaflowS3Exception("Got error: %d" % info["error"])
else:
yield self._s3root, s3url, None, info["size"], info.get(
"content_type"
), info.get("metadata", {}), None, info["last_modified"], info[
"encryption"
]
else:
# This should not happen; we should always get a response
# even if it contains an error inside it
raise MetaflowS3Exception("Did not get a response to HEAD")
return list(starmap(S3Object, _head()))
def get(
self,
key: Optional[Union[str, S3GetObject]] = None,
return_missing: bool = False,
return_info: bool = True,
) -> S3Object:
"""
Get a single object from S3.
Parameters
----------
key : Union[str, S3GetObject], optional, default None
Object to download. It can be an S3 url, a path suffix, or
an S3GetObject that defines a range of data to download. If None, or
not provided, gets the S3 root.
return_missing : bool, default False
If set to True, do not raise an exception for a missing key but
return it as an `S3Object` with `.exists == False`.
return_info : bool, default True
If set to True, fetch the content-type and user metadata associated
with the object at no extra cost, included for symmetry with `get_many`
Returns
-------
S3Object
An S3Object corresponding to the object requested.
"""
from boto3.s3.transfer import TransferConfig
DOWNLOAD_FILE_THRESHOLD = 2 * TransferConfig().multipart_threshold
DOWNLOAD_MAX_CHUNK = 2 * 1024 * 1024 * 1024 - 1
url, r = self._url_and_range(key)
# NOTE: S3 allows fragments as part of object names, e.g. /dataset #1/data.txt
# Without allow_fragments=False the parsed src.path for an object name with fragments is incomplete.
src = urlparse(url, allow_fragments=False)
def _download(s3, tmp):
if r:
resp = s3.get_object(
Bucket=src.netloc, Key=src.path.lstrip("/"), Range=r
)
# Format is bytes start-end/total; both start and end are inclusive so
# a 500 bytes file will be `bytes 0-499/500` for the entire file.
range_result = resp["ContentRange"]
range_result_match = RANGE_MATCH.match(range_result)
if range_result_match is None:
raise RuntimeError(
"Wrong format for ContentRange: %s" % str(range_result)
)
range_result = RangeInfo(
int(range_result_match.group("total")),
request_offset=int(range_result_match.group("start")),
request_length=int(range_result_match.group("end"))
- int(range_result_match.group("start"))
+ 1,
)
else:
resp = s3.get_object(Bucket=src.netloc, Key=src.path.lstrip("/"))
range_result = None
sz = resp["ContentLength"]
if range_result is None:
range_result = RangeInfo(sz, request_offset=0, request_length=sz)
if not r and sz > DOWNLOAD_FILE_THRESHOLD:
# In this case, it is more efficient to use download_file as it
# will download multiple parts in parallel (it does it after
# multipart_threshold)
s3.download_file(src.netloc, src.path.lstrip("/"), tmp)
else:
with open(tmp, mode="wb") as t:
read_in_chunks(t, resp["Body"], sz, DOWNLOAD_MAX_CHUNK)
if return_info:
return {
"content_type": resp.get("ContentType"),
# Since Metaflow can also use S3-compatible storage like MinIO,
# there maybe some keys missing in the responses given by different S3-compatible object stores.
# MinIO is generally accessed via HTTPS, and so it's encrpytion scheme is
# TLS/SSL. This is why the `ServerSideEncryption` key is not present
# in the response from MinIO.
"encryption": resp.get("ServerSideEncryption"),
"metadata": resp.get("Metadata", {}),
"range_result": range_result,
"last_modified": get_timestamp(resp["LastModified"]),
}
return None
addl_info = None
try:
path, addl_info = self._one_boto_op(_download, url)
except MetaflowS3NotFound:
if return_missing:
path = None
else:
raise
if addl_info:
return S3Object(
self._s3root,
url,
path,
content_type=addl_info["content_type"],
encryption=addl_info["encryption"],
metadata=addl_info["metadata"],
range_info=addl_info["range_result"],
last_modified=addl_info["last_modified"],
)
return S3Object(self._s3root, url, path)
def get_many(
self,
keys: Iterable[Union[str, S3GetObject]],
return_missing: bool = False,
return_info: bool = True,
) -> List[S3Object]:
"""
Get many objects from S3 in parallel.
Parameters
----------