Repository navigation
Expand file tree
/
Copy pathapi.py
More file actions
5691 lines (5012 loc) · 200 KB
/
Copy pathapi.py
File metadata and controls
5691 lines (5012 loc) · 200 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
# -*- coding: utf-8 -*-
# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C)
# 2015, 2016, 2017 MinIO, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=too-many-arguments
# pylint: disable=too-many-branches
# pylint: disable=too-many-function-args
# pylint: disable=too-many-lines
# pylint: disable=too-many-public-methods
# pylint: disable=too-many-statements
# pylint: disable=too-many-locals
"""
Simple Storage Service (aka S3) client to perform bucket and object operations.
"""
from __future__ import absolute_import, annotations
import io
im
10BC8
port itertools
import json
import os
import tarfile
from collections.abc import Iterable
from datetime import datetime, timedelta
from io import BytesIO
from random import random
from typing import Any, BinaryIO, Iterator, Optional, TextIO, Union, cast
from urllib.parse import quote, urlencode, urlunsplit
from xml.etree import ElementTree as ET
import certifi
import urllib3
from urllib3 import Retry
from urllib3._collections import HTTPHeaderDict
try:
from urllib3.response import BaseHTTPResponse # type: ignore[attr-defined]
except ImportError:
from urllib3.response import HTTPResponse as BaseHTTPResponse
from urllib3.util import Timeout
from . import time
from .checksum import (MD5, SHA256, UNSIGNED_PAYLOAD, ZERO_MD5_HASH,
ZERO_SHA256_HASH, Algorithm, base64_string,
base64_string_to_sum, hex_string, make_headers,
new_hashers)
from .commonconfig import (COPY, REPLACE, ComposeSource, CopySource,
SnowballObject, Tags)
from .credentials import StaticProvider
from .credentials.providers import Provider
from .datatypes import (Bucket, CompleteMultipartUploadResult, EventIterable,
ListAllMyBucketsResult, ListMultipartUploadsResult,
ListPartsResult, Object, Part, PostPolicy,
parse_copy_object, parse_list_objects)
from .deleteobjects import (DeleteError, DeleteObject, DeleteRequest,
DeleteResult)
from .error import InvalidResponseError, S3Error, ServerError
from .helpers import (_DEFAULT_USER_AGENT, MAX_MULTIPART_COUNT,
MAX_MULTIPART_OBJECT_SIZE, MAX_PART_SIZE, MIN_PART_SIZE,
BaseURL, HTTPQueryDict, ObjectWriteResult, ProgressType,
RegionMap, ThreadPool, check_bucket_name,
check_object_name, check_sse, check_ssec, get_part_info,
headers_to_strings, is_valid_policy_type, makedirs,
normalize_headers, queryencode, read_part_data)
from .legalhold import LegalHold
from .lifecycleconfig import LifecycleConfig
from .notificationconfig import NotificationConfig
from .objectlockconfig import ObjectLockConfig
from .replicationconfig import ReplicationConfig
from .retention import Retention
from .select import SelectObjectReader, SelectRequest
from .signer import presign_v4, sign_v4_s3
from .sse import Sse, SseCustomerKey
from .sseconfig import SSEConfig
from .tagging import Tagging
from .time import to_http_header, to_iso8601utc
from .versioningconfig import VersioningConfig
from .xml import Element, SubElement, findtext, getbytes, marshal, unmarshal
class Minio:
"""
Simple Storage Service (aka S3) client to perform bucket and object
operations.
"""
_region_map: RegionMap
_base_url: BaseURL
_user_agent: str
_trace_stream: Optional[TextIO]
_provider: Optional[Provider]
_http: urllib3.PoolManager
def __init__(
self,
*,
endpoint: str,
access_key: Optional[str] = None,
secret_key: Optional[str] = None,
session_token: Optional[str] = None,
secure: bool = True,
region: Optional[str] = None,
http_client: Optional[urllib3.PoolManager] = None,
credentials: Optional[Provider] = None,
cert_check: bool = True,
):
"""
Initializes a new Minio client object.
Args:
endpoint (str):
Hostname of an S3 service.
access_key (Optional[str], default=None):
Access key (aka user ID) of your account in the S3 service.
secret_key (Optional[str], default=None):
Secret key (aka password) of your account in the S3 service.
session_token (Optional[str], default=None):
Session token of your account in the S3 service.
secure (bool, default=True):
Flag to indicate whether to use a secure (TLS) connection
to the S3 service.
region (Optional[str], default=None):
Region name of buckets in the S3 service.
http_client (Optional[urllib3.PoolManager], default=None):
Customized HTTP client.
credentials (Optional[Provider], default=None):
Credentials provider of your account in the S3 service.
cert_check (bool, default=True):
Flag to enable/disable server certificate validation
for HTTPS connections.
Notes:
The `Minio` object is thread-safe when used with the Python
`threading` library. However, it is **not** safe to share it
between multiple processes, for example when using
`multiprocessing.Pool`. To avoid issues, create a new `Minio`
object in each process instead of sharing it.
Example:
>>> from minio import Minio
>>>
>>> # Create client with anonymous access
>>> client = Minio(endpoint="play.min.io")
>>>
>>> # Create client with access and secret key
>>> client = Minio(
... endpoint="s3.amazonaws.com",
... access_key="ACCESS-KEY",
... secret_key="SECRET-KEY",
... )
>>>
>>> # Create client with specific region
>>> client = Minio(
... endpoint="play.minio.io:9000",
... access_key="Q3AM3UQ867SPQQA43P2F",
... secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
... region="my-region",
... )
>>>
>>> # Create client with custom HTTP client using proxy
>>> import urllib3
>>> client = Minio(
... endpoint="SERVER:PORT",
... access_key="ACCESS_KEY",
... secret_key="SECRET_KEY",
... secure=True,
... http_client=urllib3.ProxyManager(
... "https://PROXYSERVER:PROXYPORT/",
... timeout=urllib3.Timeout.DEFAULT_TIMEOUT,
... cert_reqs="CERT_REQUIRED",
... retries=urllib3.Retry(
... total=5,
... backoff_factor=0.2,
... status_forcelist=[500, 502, 503, 504],
... ),
... ),
... )
"""
# Validate http client has correct base class.
if http_client and not isinstance(http_client, urllib3.PoolManager):
raise TypeError(
"HTTP client should be urllib3.PoolManager like object, "
f"got {type(http_client).__name__}",
)
self._region_map = RegionMap()
self._base_url = BaseURL(
("https://" if secure else "http://") + endpoint,
region,
)
self._user_agent = _DEFAULT_USER_AGENT
self._trace_stream = None
if access_key:
if secret_key is None:
raise ValueError("secret key must be provided with access key")
credentials = StaticProvider(access_key, secret_key, session_token)
self._provider = credentials
# Load CA certificates from SSL_CERT_FILE file if set
timeout = timedelta(minutes=5).seconds
self._http = http_client or urllib3.PoolManager(
timeout=Timeout(connect=timeout, read=timeout),
maxsize=10,
cert_reqs='CERT_REQUIRED' if cert_check else 'CERT_NONE',
ca_certs=os.environ.get('SSL_CERT_FILE') or certifi.where(),
retries=Retry(
total=5,
backoff_factor=0.2,
status_forcelist=[500, 502, 503, 504]
)
)
def __del__(self):
if hasattr(self, "_http"): # Only required for unit test run
self._http.clear()
@staticmethod
def _gen_read_headers(
*,
ssec: Optional[SseCustomerKey] = None,
offset: int = 0,
length: Optional[int] = None,
match_etag: Optional[str] = None,
not_match_etag: Optional[str] = None,
modified_since: Optional[datetime] = None,
unmodified_since: Optional[datetime] = None,
fetch_checksum: bool = False,
) -> HTTPHeaderDict:
"""Generates conditional headers for get/head object."""
headers = HTTPHeaderDict()
if ssec:
headers.extend(ssec.headers())
if offset or length:
end = (offset + length - 1) if length else ""
headers['Range'] = f"bytes={offset}-{end}"
if match_etag:
headers["if-match"] = match_etag
if not_match_etag:
headers["if-none-match"] = not_match_etag
if modified_since:
headers["if-modified-since"] = to_http_header(modified_since)
if unmodified_since:
headers["if-unmodified-since"] = to_http_header(unmodified_since)
if fetch_checksum:
headers["x-amz-checksum-mode"] = "ENABLED"
return headers
@staticmethod
def _gen_write_headers(
*,
headers: Optional[HTTPHeaderDict] = None,
user_metadata: Optional[HTTPHeaderDict] = None,
sse: Optional[Sse] = None,
tags: Optional[Tags] = None,
retention: Optional[Retention] = None,
legal_hold: bool = False,
) -> HTTPHeaderDict:
"""Generate headers for given parameters."""
headers = headers.copy() if headers else HTTPHeaderDict()
if user_metadata:
headers.extend(user_metadata)
headers = normalize_headers(headers)
if sse:
headers.extend(sse.headers())
if tags:
headers["x-amz-tagging"] = urlencode(
list(tags.items()), quote_via=quote,
)
if retention and retention.mode:
headers["x-amz-object-lock-mode"] = retention.mode
headers["x-amz-object-lock-retain-until-date"] = cast(
str, to_iso8601utc(retention.retain_until_date),
)
if legal_hold:
headers["x-amz-object-lock-legal-hold"] = "ON"
return headers
def _handle_redirect_response(
self,
method: str,
response: BaseHTTPResponse,
bucket_name: Optional[str] = None,
retry: bool = False,
) -> tuple[Optional[str], Optional[str]]:
"""
Handle redirect response indicates whether retry HEAD request
on failure.
"""
code, message = {
301: ("PermanentRedirect", "Moved Permanently"),
307: ("Redirect", "Temporary redirect"),
400: ("BadRequest", "Bad request"),
}.get(response.status, (None, None))
region = response.headers.get("x-amz-bucket-region")
if message and region:
message += "; use region " + region
if (
retry and region and method == "HEAD" and bucket_name and
self._region_map.get(bucket_name)
):
code, message = ("RetryHead", None)
return code, message
def _url_open(
self,
*,
method: str,
region: str,
bucket_name: Optional[str] = None,
object_name: Optional[str] = None,
body: Optional[bytes] = None,
headers: Optional[HTTPHeaderDict] = None,
query_params: Optional[HTTPQueryDict] = None,
preload_content: bool = True,
no_body_trace: bool = False,
extra_headers: Optional[HTTPHeaderDict] = None,
extra_query_params: Optional[HTTPQueryDict] = None,
) -> BaseHTTPResponse:
"""Execute HTTP request."""
url = self._base_url.build(
method=method,
region=region,
bucket_name=bucket_name,
object_name=object_name,
query_params=query_params,
extra_query_params=extra_query_params,
)
headers = headers.copy() if headers else HTTPHeaderDict()
if extra_headers:
headers.extend(extra_headers)
headers["Host"] = url.netloc
headers["User-Agent"] = self._user_agent
content_sha256 = headers.get("x-amz-content-sha256")
content_md5 = headers.get("Content-MD5")
if method in ["PUT", "POST"]:
headers["Content-Length"] = str(len(body or b""))
if not headers.get("Content-Type"):
headers["Content-Type"] = "application/octet-stream"
if body is None:
content_sha256 = content_sha256 or ZERO_SHA256_HASH
content_md5 = content_md5 or ZERO_MD5_HASH
else:
if not content_sha256:
if self._base_url.is_https:
content_sha256 = UNSIGNED_PAYLOAD
else:
sha256_checksum = headers.get("x-amz-checksum-sha256")
content_sha256 = hex_string(
base64_string_to_sum(sha256_checksum) if sha256_checksum
else SHA256.hash(body),
)
if not content_md5 and content_sha256 == UNSIGNED_PAYLOAD:
content_md5 = base64_string(MD5.hash(body))
if not headers.get("x-amz-content-sha256"):
headers["x-amz-content-sha256"] = cast(str, content_sha256)
if not headers.get("Content-MD5") and content_md5:
headers["Content-MD5"] = content_md5
date = time.utcnow()
headers["x-amz-date"] = time.to_amz_date(date)
if self._provider is not None:
creds = self._provider.retrieve()
if creds.session_token:
headers["X-Amz-Security-Token"] = creds.session_token
headers = sign_v4_s3(
method=method,
url=url,
region=region,
headers=headers,
credentials=creds,
content_sha256=cast(str, content_sha256),
date=date,
)
if self._trace_stream:
self._trace_stream.write("---------START-HTTP---------\n")
query = ("?" + url.query) if url.query else ""
self._trace_stream.write(f"{method} {url.path}{query} HTTP/1.1\n")
self._trace_stream.write(
headers_to_strings(headers, titled_key=True),
)
self._trace_stream.write("\n")
if not no_body_trace and body is not None:
self._trace_stream.write("\n")
self._trace_stream.write(
body.decode() if isinstance(body, bytes) else str(body),
)
self._trace_stream.write("\n")
self._trace_stream.write("\n")
response = self._http.urlopen(
method,
urlunsplit(url),
body=body,
headers=headers,
preload_content=preload_content,
)
if self._trace_stream:
self._trace_stream.write(f"HTTP/1.1 {response.status}\n")
self._trace_stream.write(
headers_to_strings(response.headers),
)
self._trace_stream.write("\n")
if response.status in [200, 204, 206]:
if self._trace_stream:
if preload_content:
self._trace_stream.write("\n")
self._trace_stream.write(response.data.decode())
self._trace_stream.write("\n")
self._trace_stream.write("----------END-HTTP----------\n")
return response
response.read(cache_content=True)
if not preload_content:
response.release_conn()
if self._trace_stream and method != "HEAD" and response.data:
self._trace_stream.write(response.data.decode())
self._trace_stream.write("\n")
if (
method != "HEAD" and
"application/xml" not in response.headers.get(
"content-type", "",
).split(";")
):
if self._trace_stream:
self._trace_stream.write("----------END-HTTP----------\n")
if response.status == 304 and not response.data:
raise ServerError(
f"server failed with HTTP status code {response.status}",
response.status,
)
raise InvalidResponseError(
response.status,
cast(str, response.headers.get("content-type")),
response.data.decode() if response.data else None,
)
if not response.data and method != "HEAD":
if self._trace_stream:
self._trace_stream.write("----------END-HTTP----------\n")
raise InvalidResponseError(
response.status,
response.headers.get("content-type"),
None,
)
response_error = S3Error.fromxml(response) if response.data else None
if self._trace_stream:
self._trace_stream.write("----------END-HTTP----------\n")
error_map = {
301: lambda: self._handle_redirect_response(
method, response, bucket_name, True,
),
307: lambda: self._handle_redirect_response(
method, response, bucket_name, True,
),
400: lambda: self._handle_redirect_response(
method, response, bucket_name, True,
),
403: lambda: ("AccessDenied", "Access denied"),
404: lambda: (
("NoSuchKey", "Object does not exist")
if object_name
else ("NoSuchBucket", "Bucket does not exist")
if bucket_name
else ("ResourceNotFound", "Request resource not found")
),
405: lambda: (
"MethodNotAllowed",
"The specified method is not allowed against this resource",
),
409: lambda: (
("NoSuchBucket", "Bucket does not exist")
if bucket_name
else ("ResourceConflict", "Request resource conflicts"),
),
501: lambda: (
"MethodNotAllowed",
"The specified method is not allowed against this resource",
),
}
if not response_error:
func = error_map.get(response.status)
code, message = func() if func else (None, None)
if not code:
raise ServerError(
f"server failed with HTTP status code {response.status}",
response.status,
)
response_error = S3Error(
response=response,
code=cast(str, code),
message=cast(Union[str, None], message),
resource=url.path,
request_id=response.headers.get("x-amz-request-id"),
host_id=response.headers.get("x-amz-id-2"),
bucket_name=bucket_name,
object_name=object_name,
)
if response_error.code in ["NoSuchBucket", "RetryHead"]:
if bucket_name is not None:
self._region_map.remove(bucket_name)
raise response_error
def _execute(
self,
*,
method: str,
bucket_name: Optional[str] = None,
object_name: Optional[str] = None,
body: Optional[bytes] = None,
headers: Optional[HTTPHeaderDict] = None,
query_params: Optional[HTTPQueryDict] = None,
preload_content: bool = True,
no_body_trace: bool = False,
region: Optional[str] = None,
extra_headers: Optional[HTTPHeaderDict] = None,
extra_query_params: Optional[HTTPQueryDict] = None,
) -> BaseHTTPResponse:
"""Execute HTTP request."""
region = self._get_region(
bucket_name=bucket_name,
region=region,
)
try:
return self._url_open(
method=method,
region=region,
bucket_name=bucket_name,
object_name=object_name,
body=body,
headers=headers,
query_params=query_params,
preload_content=preload_content,
no_body_trace=no_body_trace,
extra_headers=extra_headers,
extra_query_params=extra_query_params,
)
except S3Error as exc:
if exc.code != "RetryHead":
raise
# Retry only once on RetryHead error.
try:
return self._url_open(
method=method,
region=region,
bucket_name=bucket_name,
object_name=object_name,
body=body,
headers=headers,
query_params=query_params,
preload_content=preload_content,
no_body_trace=no_body_trace,
extra_headers=extra_headers,
extra_query_params=extra_query_params,
)
except S3Error as exc:
if exc.code != "RetryHead":
raise
code, message = self._handle_redirect_response(
method, exc.response, bucket_name,
)
raise exc.copy(cast(str, code), cast(str, message))
def _get_region(
self,
*,
bucket_name: Optional[str] = None,
region: Optional[str] = None,
extra_headers: Optional[HTTPHeaderDict] = None,
extra_query_params: Optional[HTTPQueryDict] = None,
) -> str:
"""
Return region of given bucket either from region cache or set in
constructor.
"""
if (
region is not None and self._base_url.region is not None and
region != self._base_url.region
):
raise ValueError(
f"region must be {self._base_url.region}, but passed {region}",
)
if region is not None:
return region
if self._base_url.region is not None:
return self._base_url.region
if not bucket_name or not self._provider:
return "us-east-1"
region = self._region_map.get(bucket_name)
if region:
return region
# Execute GetBucketLocation REST API to get region of the bucket.
response = self._url_open(
method="GET",
region="us-east-1",
bucket_name=bucket_name,
query_params=HTTPQueryDict({"location": ""}),
extra_headers=extra_headers,
extra_query_params=extra_query_params,
)
element = ET.fromstring(response.data.decode())
if not element.text:
region = "us-east-1"
elif element.text == "EU" and self._base_url.is_aws_host:
region = "eu-west-1"
else:
region = element.text
self._region_map.set(bucket_name, region)
return region
def set_app_info(self, app_name: str, app_version: str):
"""
Set your application name and version to user agent header.
Args:
app_name (str):
Application name.
app_version (str):
Application version.
Example:
>>> client.set_app_info("my_app", "1.0.2")
"""
if not (app_name and app_version):
raise ValueError("Application name/version cannot be empty.")
self._user_agent = f"{_DEFAULT_USER_AGENT} {app_name}/{app_version}"
def trace_on(self, stream: TextIO):
"""
Enable http trace.
Args:
stream (TextIO):
Stream for writing HTTP call tracing.
Example:
>>> client.trace_on(sys.stdout)
"""
if not stream:
raise ValueError('Input stream for trace output is invalid.')
# Save new output stream.
self._trace_stream = stream
def trace_off(self):
"""Disable HTTP trace."""
self._trace_stream = None
def enable_accelerate_endpoint(self):
"""Enables accelerate endpoint for Amazon S3 endpoint."""
self._base_url.accelerate_host_flag = True
def disable_accelerate_endpoint(self):
"""Disables accelerate endpoint for Amazon S3 endpoint."""
self._base_url.accelerate_host_flag = False
def enable_dualstack_endpoint(self):
"""Enables dualstack endpoint for Amazon S3 endpoint."""
self._base_url.dualstack_host_flag = True
def disable_dualstack_endpoint(self):
"""Disables dualstack endpoint for Amazon S3 endpoint."""
self._base_url.dualstack_host_flag = False
def enable_virtual_style_endpoint(self):
"""Enables virtual style endpoint."""
self._base_url.virtual_style_flag = True
def disable_virtual_style_endpoint(self):
"""Disables virtual style endpoint."""
self._base_url.virtual_style_flag = False
def select_object_content(
self,
*,
bucket_name: str,
object_name: str,
request: SelectRequest,
region: Optional[str] = None,
extra_headers: Optional[HTTPHeaderDict] = None,
extra_query_params: Optional[HTTPQueryDict] = None,
) -> SelectObjectReader:
"""
Select content of an object by SQL expression.
Args:
bucket_name (str):
Name of the bucket.
object_name (str):
Object name in the bucket.
request (SelectRequest):
Select request.
region (Optional[str], default=None):
Region of the bucket to skip auto probing.
extra_headers (Optional[HTTPHeaderDict], default=None):
Extra headers for advanced usage.
extra_query_params (Optional[HTTPQueryDict], default=None):
Extra query parameters for advanced usage.
Returns:
SelectObjectReader:
A reader object representing the results of the select
operation.
Example:
>>> with client.select_object_content(
... bucket_name="my-bucket",
... object_name="my-object.csv",
... request=SelectRequest(
... expression="select * from S3Object",
... input_serialization=CSVInputSerialization(),
... output_serialization=CSVOutputSerialization(),
... request_progress=True,
... ),
... ) as result:
... for data in result.stream():
... print(data.decode())
... print(result.stats())
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
check_object_name(object_name)
if not isinstance(request, SelectRequest):
raise ValueError("request must be SelectRequest type")
body = marshal(request)
headers = HTTPHeaderDict(
{"Content-MD5": base64_string(MD5.hash(body))},
)
response = self._execute(
method="POST",
bucket_name=bucket_name,
object_name=object_name,
body=body,
headers=headers,
query_params=HTTPQueryDict({"select": "", "select-type": "2"}),
preload_content=False,
region=region,
extra_headers=extra_headers,
extra_query_params=extra_query_params,
)
return SelectObjectReader(response)
def make_bucket(
self,
*,
bucket_name: str,
location: Optional[str] = None,
object_lock: bool = False,
extra_headers: Optional[HTTPHeaderDict] = None,
extra_query_params: Optional[HTTPQueryDict] = None,
):
"""
Create a bucket with region and optional object lock.
Args:
bucket_name (str):
Name of the bucket.
location (Optional[str], default=None):
Region in which the bucket is to be created.
object_lock (bool, default=False):
Flag to enable the object-lock feature.
extra_headers (Optional[HTTPHeaderDict], default=None):
Extra headers for advanced usage.
extra_query_params (Optional[HTTPQuer
E784
yDict], default=None):
Extra query parameters for advanced usage.
Example:
>>> # Create bucket
>>> client.make_bucket(bucket_name="my-bucket")
>>>
>>> # Create bucket in a specific region
>>> client.make_bucket(
... bucket_name="my-bucket",
... location="eu-west-1",
... )
>>>
>>> # Create bucket with object-lock in a region
>>> client.make_bucket(
... bucket_name="my-bucket",
... location="eu-west-2",
... object_lock=True,
... )
"""
check_bucket_name(bucket_name, True,
s3_check=self._base_url.is_aws_host)
if self._base_url.region:
# Error out if region does not match with region passed via
# constructor.
if location and self._base_url.region != location:
raise ValueError(
f"region must be {self._base_url.region}, "
f"but passed {location}"
)
location = self._base_url.region or location or "us-east-1"
headers = HTTPHeaderDict()
if object_lock:
headers["x-amz-bucket-object-lock-enabled"] = "true"
body = None
if location != "us-east-1":
element = Element("CreateBucketConfiguration")
SubElement(element, "LocationConstraint", location)
body = getbytes(element)
self._url_open(
method="PUT",
region=location,
bucket_name=bucket_name,
body=body,
headers=headers,
extra_headers=extra_headers,
extra_query_params=extra_query_params,
)
self._region_map.set(bucket_name, location)
def _list_buckets(
self,
*,
bucket_region: Optional[str] = None,
max_buckets: int = 10000,
prefix: Optional[str] = None,
continuation_token: Optional[str] = None,
extra_headers: Optional[HTTPHeaderDict] = None,
extra_query_params: Optional[HTTPQueryDict] = None,
) -> ListAllMyBucketsResult:
"""Do ListBuckets S3 API."""
query_params = HTTPQueryDict()
query_params["max-buckets"] = str(
max_buckets if max_buckets > 0 else 10000,
)
if bucket_region is not None:
query_params["bucket-region"] = bucket_region
if prefix:
query_params["prefix"] = prefix
if continuation_token:
query_params["continuation-token"] = continuation_token
response = self._execute(
method="GET",
query_params=query_params,
extra_headers=extra_headers,
extra_query_params=extra_query_params,
)
return unmarshal(ListAllMyBucketsResult, response.data.decode())
def list_buckets(
self,
*,
bucket_region: Optional[str] = None,
max_buckets: int = 10000,
prefix: Optional[str] = None,
extra_headers: Optional[HTTPHeaderDict] = None,
extra_query_params: Optional[HTTPQueryDict] = None,
) -> Iterator[Bucket]:
"""
List information of all accessible buckets.
Args:
bucket_region (Optional[str], default=None):
Fetch buckets from the specified region.
max_buckets (int, default=10000):
Maximum number of buckets to fetch.
prefix (Optional[str], default=None):
Return only buckets whose names start with this prefix.
extra_headers (Optional[HTTPHeaderDict], default=None):
Extra headers for advanced usage.
extra_query_params (Optional[HTTPQueryDict], default=None):
Extra query parameters for advanced usage.
Returns:
Iterator[Bucket]:
An iterator of :class:`minio.datatypes.Bucket` objects.
Example:
>>> buckets = client.list_buckets()
>>> for bucket in buckets:
... print(bucket.name, bucket.creation_date)
"""
continuation_token: Optional[str] = ""
while continuation_token is not None:
result = self._list_buckets(
bucket_region=bucket_region,
max_buckets=max_buckets,
prefix=prefix,
continuation_token=continuation_token,
extra_headers=extra_headers,
extra_query_params=extra_query_params,
)
continuation_token = result.continuation_token
yield from result.buckets
def bucket_exists(
self,
*,
bucket_name: str,
region: Optional[str] = None,
extra_headers: Optional[HTTPHeaderDict] = None,
extra_query_params: Optional[HTTPQueryDict] = None,
) -> bool:
"""
Check if a bucket exists.
Args:
bucket_name (str):
Name of the bucket.
region (Optional[str], default=None):
Region of the bucket to skip auto probing.
extra_headers (Optional[HTTPHeaderDict], default=None):
Extra headers for advanced usage.
extra_query_params (Optional[HTTPQueryDict], default=None):
Extra query parameters for advanced usage.
Returns:
bool:
True if the bucket exists, False otherwise.
Example:
>>> if client.bucket_exists(bucket_name="my-bucket"):
... print("my-bucket exists")
... else:
... print("my-bucket does not exist")
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
try:
self._execute(
method="HEAD",
bucket_name=bucket_name,
region=region,
extra_headers=extra_headers,
extra_query_params=extra_query_params,
)
return True
except S3Error as exc:
if exc.code != "NoSuchBucket":
raise
return False
def remove_bucket(
self,
*,
bucket_name: str,