8000 minio-py/minio/api.py at master · limfong/minio-py · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
2824 lines (2511 loc) · 101 KB

api.py

File metadata and controls

2824 lines (2511 loc) · 101 KB
def _url_open( # pylint: disable=too-many-branches
self,
method,
region,
bucket_name=None,
object_name=None,
body=None,
headers=None,
query_params=None,
preload_content=True,
no_body_trace=False,
):
"""Execute HTTP request."""
creds = self._provider.retrieve() if self._provider else None
url = self._base_url.build(
method,
region,
bucket_name=bucket_name,
object_name=object_name,
query_params=query_params,
)
headers, date = self._build_headers(url.netloc, headers, body, creds)
if creds:
headers = sign_v4_s3(
method,
url,
region,
headers,
creds,
headers.get("x-amz-content-sha256"),
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")
http_headers = HTTPHeaderDict()
for key, value in (headers or {}).items():
if isinstance(value, (list, tuple)):
_ = [http_headers.add(key, val) for val in value]
else:
http_headers.add(key, value)
response = self._http.urlopen(
method,
urlunsplit(url),
body=body,
headers=http_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.getheaders()),
)
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.getheader(
"content-type", "",
).split(";")
):
if self._trace_stream:
self._trace_stream.write("----------END-HTTP----------\n")
raise InvalidResponseError(
response.status,
response.getheader("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.getheader("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, bucket_name, response, True,
),
307: lambda: self._handle_redirect_response(
method, bucket_name, response, True,
),
400: lambda: self._handle_redirect_response(
method, bucket_name, response, 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_error = S3Error(
code,
message,
url.path,
response.getheader("x-amz-request-id"),
response.getheader("x-amz-id-2"),
response,
bucket_name=bucket_name,
object_name=object_name,
)
if response_error.code in ["NoSuchBucket", "RetryHead"]:
self._region_map.pop(bucket_name, None)
raise response_error
def _execute(
self,
method,
bucket_name=None,
object_name=None,
body=None,
headers=None,
query_params=None,
preload_content=True,
no_body_trace=False,
):
"""Execute HTTP request."""
region = self._get_region(bucket_name, None)
try:
return self._url_open(
method,
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,
)
except S3Error as exc:
if exc.code != "RetryHead":
raise
# Retry only once on RetryHead error.
try:
return self._url_open(
method,
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,
)
except S3Error as exc:
if exc.code != "RetryHead":
raise
code, message = self._handle_redirect_response(
method, bucket_name, exc.response,
)
raise exc.copy(code, message)
def _get_region(self, bucket_name, region):
"""
Return region of given bucket either from region cache or set in
constructor.
"""
if region:
# Error out if region does not match with region passed via
# constructor.
if self._base_url.region and self._base_url.region != region:
raise ValueError(
f"region must be {self._base_url.region}, "
f"but passed {region}"
)
return region
if self._base_url.region:
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(
"GET",
"us-east-1",
bucket_name=bucket_name,
query_params={"location": ""},
)
element = ET.fromstring(response.data.decode())
if not element.text:
region = "us-east-1"
elif element.text == "EU":
region = "eu-west-1"
else:
region = element.text
self._region_map[bucket_name] = region
return region
def set_app_info(self, app_name, app_version):
"""
Set your application name and version to user agent header.
:param app_name: Application name.
:param app_version: 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):
"""
Enable http trace.
:param stream: Stream for writing HTTP call tracing.
"""
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, object_name, request):
"""
Select content of an object by SQL expression.
:param bucket_name: Name of the bucket.
:param object_name: Object name in the bucket.
:param request: :class:`SelectRequest <SelectRequest>` object.
:return: A reader contains requested records and progress information.
Example::
with client.select_object_content(
"my-bucket",
"my-object.csv",
SelectRequest(
"select * from S3Object",
CSVInputSerialization(),
CSVOutputSerialization(),
request_progress=True,
),
) as result:
for data in result.stream():
print(data.decode())
print(result.stats())
"""
check_bucket_name(bucket_name)
check_non_empty_string(object_name)
if not isinstance(request, SelectRequest):
raise ValueError("request must be SelectRequest type")
body = marshal(request)
response = self._execute(
"POST",
bucket_name=bucket_name,
object_name=object_name,
body=body,
headers={"Content-MD5": md5sum_hash(body)},
query_params={"select": "", "select-type": "2"},
preload_content=False,
)
return SelectObjectReader(response)
def make_bucket(self, bucket_name, location=None, object_lock=False):
"""
Create a bucket with region and object lock.
:param bucket_name: Name of the bucket.
:param location: Region in which the bucket will be created.
:param object_lock: Flag to set object-lock feature.
Examples::
# Create bucket.
client.make_bucket("my-bucket")
# Create bucket on specific region.
client.make_bucket("my-bucket", "us-west-1")
# Create bucket with object-lock feature on specific region.
client.make_bucket("my-bucket", "eu-west-2", object_lock=True)
"""
check_bucket_name(bucket_name, True)
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 = (
{"x-amz-bucket-object-lock-enabled": "true"}
if object_lock else None
)
body = None
if location != "us-east-1":
element = Element("CreateBucketConfiguration")
SubElement(element, "LocationConstraint", location)
body = getbytes(element)
self._url_open(
"PUT",
location,
bucket_name=bucket_name,
body=body,
headers=headers,
)
self._region_map[bucket_name] = location
def list_buckets(self):
"""
List information of all accessible buckets.
:return: List of :class:`Bucket <Bucket>` object.
Example::
buckets = client.list_buckets()
for bucket in buckets:
print(bucket.name, bucket.creation_date)
"""
response = self._execute("GET")
result = unmarshal(ListAllMyBucketsResult, response.data.decode())
return result.buckets
def bucket_exists(self, bucket_name):
"""
Check if a bucket exists.
:param bucket_name: Name of the bucket.
:return: True if the bucket exists.
Example::
if client.bucket_exists("my-bucket"):
print("my-bucket exists")
else:
print("my-bucket does not exist")
"""
check_bucket_name(bucket_name)
try:
self._execute("HEAD", bucket_name)
return True
except S3Error as exc:
if exc.code != "NoSuchBucket":
raise
return False
def remove_bucket(self, bucket_name):
"""
Remove an empty bucket.
:param bucket_name: Name of the bucket.
Example::
client.remove_bucket("my-bucket")
"""
check_bucket_name(bucket_name)
self._execute("DELETE", bucket_name)
self._region_map.pop(bucket_name, None)
def get_bucket_policy(self, bucket_name):
"""
Get bucket policy configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: Bucket policy configuration as JSON string.
Example::
policy = client.get_bucket_policy("my-bucket")
"""
check_bucket_name(bucket_name)
response = self._execute(
"GET", bucket_name, query_params={"policy": ""},
)
return response.data.decode()
def delete_bucket_policy(self, bucket_name):
"""
Delete bucket policy configuration of a bucket.
:param bucket_name: Name of the bucket.
Example::
client.delete_bucket_policy("my-bucket")
"""
check_bucket_name(bucket_name)
self._execute("DELETE", bucket_name, query_params={"policy": ""})
def set_bucket_policy(self, bucket_name, policy):
"""
Set bucket policy configuration to a bucket.
:param bucket_name: Name of the bucket.
:param policy: Bucket policy configuration as JSON string.
Example::
client.set_bucket_policy("my-bucket", policy)
"""
check_bucket_name(bucket_name)
is_valid_policy_type(policy)
self._execute(
"PUT",
bucket_name,
body=policy,
headers={"Content-MD5": md5sum_hash(policy)},
query_params={"policy": ""},
)
def get_bucket_notification(self, bucket_name):
"""
Get notification configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: :class:`NotificationConfig <NotificationConfig>` object.
Example::
config = client.get_bucket_notification("my-bucket")
"""
check_bucket_name(bucket_name)
response = self._execute(
"GET", bucket_name, query_params={"notification": ""},
)
return unmarshal(NotificationConfig, response.data.decode())
def set_bucket_notification(self, bucket_name, config):
"""
Set notification configuration of a bucket.
:param bucket_name: Name of the bucket.
:param config: class:`NotificationConfig <NotificationConfig>` object.
Example::
config = NotificationConfig(
queue_config_list=[
QueueConfig(
"QUEUE-ARN-OF-THIS-BUCKET",
["s3:ObjectCreated:*"],
config_id="1",
prefix_filter_rule=PrefixFilterRule("abc"),
),
],
)
client.set_bucket_notification("my-bucket", config)
"""
check_bucket_name(bucket_name)
if not isinstance(config, NotificationConfig):
raise ValueError("config must be NotificationConfig type")
body = marshal(config)
self._execute(
"PUT",
bucket_name,
body=body,
headers={"Content-MD5": md5sum_hash(body)},
query_params={"notification": ""},
)
def delete_bucket_notification(self, bucket_name):
"""
Delete notification configuration of a bucket. On success, S3 service
stops notification of events previously set of the bucket.
:param bucket_name: Name of the bucket.
Example::
client.delete_bucket_notification("my-bucket")
"""
self.set_bucket_notification(bucket_name, NotificationConfig())
def set_bucket_encryption(self, bucket_name, config):
"""
Set encryption configuration of a bucket.
:param bucket_name: Name of the bucket.
:param config: :class:`SSEConfig <SSEConfig>` object.
Example::
client.set_bucket_encryption(
"my-bucket", SSEConfig(Rule.new_sse_s3_rule()),
)
"""
check_bucket_name(bucket_name)
if not isinstance(config, SSEConfig):
raise ValueError("config must be SSEConfig type")
body = marshal(config)
self._execute(
"PUT",
bucket_name,
body=body,
headers={"Content-MD5": md5sum_hash(body)},
query_params={"encryption": ""},
)
def get_bucket_encryption(self, bucket_name):
"""
Get encryption configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: :class:`SSEConfig <SSEConfig>` object.
Example::
config = client.get_bucket_encryption("my-bucket")
"""
check_bucket_name(bucket_name)
try:
response = self._execute(
"GET",
bucket_name,
query_params={"encryption": ""},
)
return unmarshal(SSEConfig, response.data.decode())
except S3Error as exc:
if exc.code != "ServerSideEncryptionConfigurationNotFoundError":
raise
return None
def delete_bucket_encryption(self, bucket_name):
"""
Delete encryption configuration of a bucket.
:param bucket_name: Name of the bucket.
Example::
client.delete_bucket_encryption("my-bucket")
"""
check_bucket_name(bucket_name)
try:
self._execute(
"DELETE",
bucket_name,
query_params={"encryption": ""},
)
except S3Error as exc:
if exc.code != "ServerSideEncryptionConfigurationNotFoundError":
raise
def listen_bucket_notification(self, bucket_name, prefix='', suffix='',
events=('s3:ObjectCreated:*',
's3:ObjectRemoved:*',
's3:ObjectAccessed:*')):
"""
Listen events of object prefix and suffix of a bucket. Caller should
iterate returned iterator to read new events.
:param bucket_name: Name of the bucket.
:param prefix: Listen events of object starts with prefix.
:param suffix: Listen events of object ends with suffix.
:param events: Events to listen.
:return: Iterator of event records as :dict:.
Example::
with client.listen_bucket_notification(
"my-bucket",
prefix="my-prefix/",
events=["s3:ObjectCreated:*", "s3:ObjectRemoved:*"],
) as events:
for event in events:
print(event)
"""
check_bucket_name(bucket_name)
if self._base_url.is_aws_host:
raise ValueError(
"ListenBucketNotification API is not supported in Amazon S3",
)
return EventIterable(
lambda: self._execute(
"GET",
bucket_name,
query_params={
"prefix": prefix or "",
"suffix": suffix or "",
"events": events,
},
preload_content=False,
),
)
def set_bucket_versioning(self, bucket_name, config):
"""
Set versioning configuration to a bucket.
:param bucket_name: Name of the bucket.
:param config: :class:`VersioningConfig <VersioningConfig>`.
Example::
client.set_bucket_versioning(
"my-bucket", VersioningConfig(ENABLED),
)
"""
check_bucket_name(bucket_name)
if not isinstance(config, VersioningConfig):
raise ValueError("config must be VersioningConfig type")
body = marshal(config)
self._execute(
"PUT",
bucket_name,
body=body,
headers={"Content-MD5": md5sum_hash(body)},
query_params={"versioning": ""},
)
def get_bucket_versioning(self, bucket_name):
"""
Get versioning configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: :class:`VersioningConfig <VersioningConfig>`.
Example::
config = client.get_bucket_versioning("my-bucket")
print(config.status)
"""
check_bucket_name(bucket_name)
response = self._execute(
"GET",
bucket_name,
query_params={"versioning": ""},
)
return unmarshal(VersioningConfig, response.data.decode())
def fput_object(self, bucket_name, object_name, file_path,
content_type="application/octet-stream",
metadata=None, sse=None, progress=None,
part_size=0, num_parallel_uploads=3,
tags=None, retention=None, legal_hold=False):
"""
Uploads data from a file to an object in a bucket.
:param bucket_name: Name of the bucket.
:param object_name: Object name in the bucket.
:param file_path: Name of file to upload.
:param content_type: Content type of the object.
:param metadata: Any additional metadata to be uploaded along
with your PUT request.
:param sse: Server-side encryption.
:param progress: A progress object
:param part_size: Multipart part size
:param num_parallel_uploads: Number of parallel uploads.
:param tags: :class:`Tags` for the object.
:param retention: :class:`Retention` configuration object.
:param legal_hold: Flag to set legal hold for the object.
:return: :class:`ObjectWriteResult` object.
Example::
# Upload data.
result = client.fput_object(
"my-bucket", "my-object", "my-filename",
)
# Upload data with metadata.
result = client.fput_object(
"my-bucket", "my-object", "my-filename",
metadata={"My-Project": "one"},
)
# Upload data with tags, retention and legal-hold.
date = datetime.utcnow().replace(
hour=0, minute=0, second=0, microsecond=0,
) + timedelta(days=30)
tags = Tags(for_object=True)
tags["User"] = "jsmith"
result = client.fput_object(
"my-bucket", "my-object", "my-filename",
tags=tags,
retention=Retention(GOVERNANCE, date),
legal_hold=True,
)
"""
file_size = os.stat(file_path).st_size
with open(file_path, "rb") as file_data:
return self.put_object(
bucket_name, object_name, file_data, file_size,
content_type=content_type,
metadata=metadata, sse=sse, progress=progress,
part_size=part_size, num_parallel_uploads=num_parallel_uploads,
tags=tags, retention=retention, legal_hold=legal_hold,
)
def fget_object(self, bucket_name, object_name, file_path,
request_headers=None, ssec=None, version_id=None,
extra_query_params=None, tmp_file_path=None):
"""
Downloads data of an object to file.
:param bucket_name: Name of the bucket.
:param object_name: Object name in the bucket.
:param file_path: Name of file to download.
:param request_headers: Any additional headers to be added with GET
0