helpers.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. # -*- coding: utf-8 -*-
  2. # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C)
  3. # 2015, 2016, 2017 MinIO, Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Helper functions."""
  17. from __future__ import absolute_import, annotations, division, unicode_literals
  18. import base64
  19. import errno
  20. import hashlib
  21. import math
  22. import os
  23. import platform
  24. import re
  25. import urllib.parse
  26. from dataclasses import dataclass
  27. from datetime import datetime
  28. from queue import Queue
  29. from threading import BoundedSemaphore, Thread
  30. from typing import BinaryIO, Dict, List, Mapping, Optional, Tuple, Union
  31. from typing_extensions import Protocol
  32. from urllib3._collections import HTTPHeaderDict
  33. from . import __title__, __version__
  34. from .sse import Sse, SseCustomerKey
  35. from .time import to_iso8601utc
  36. _DEFAULT_USER_AGENT = (
  37. f"MinIO ({platform.system()}; {platform.machine()}) "
  38. f"{__title__}/{__version__}"
  39. )
  40. MAX_MULTIPART_COUNT = 10000 # 10000 parts
  41. MAX_MULTIPART_OBJECT_SIZE = 5 * 1024 * 1024 * 1024 * 1024 # 5TiB
  42. MAX_PART_SIZE = 5 * 1024 * 1024 * 1024 # 5GiB
  43. MIN_PART_SIZE = 5 * 1024 * 1024 # 5MiB
  44. _AWS_S3_PREFIX = (r'^(((bucket\.|accesspoint\.)'
  45. r'vpce(-(?!_)[a-z_\d]+(?<!-)(?<!_))+\.s3\.)|'
  46. r'((?!s3)(?!-)(?!_)[a-z_\d-]{1,63}(?<!-)(?<!_)\.)'
  47. r's3-control(-(?!_)[a-z_\d]+(?<!-)(?<!_))*\.|'
  48. r'(s3(-(?!_)[a-z_\d]+(?<!-)(?<!_))*\.))')
  49. _BUCKET_NAME_REGEX = re.compile(r'^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$')
  50. _OLD_BUCKET_NAME_REGEX = re.compile(r'^[a-z0-9][a-z0-9_\.\-\:]{1,61}[a-z0-9]$',
  51. re.IGNORECASE)
  52. _IPV4_REGEX = re.compile(
  53. r'^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}'
  54. r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$')
  55. _HOSTNAME_REGEX = re.compile(
  56. r'^((?!-)(?!_)[a-z_\d-]{1,63}(?<!-)(?<!_)\.)*'
  57. r'((?!_)(?!-)[a-z_\d-]{1,63}(?<!-)(?<!_))$',
  58. re.IGNORECASE)
  59. _AWS_ENDPOINT_REGEX = re.compile(r'.*\.amazonaws\.com(|\.cn)$', re.IGNORECASE)
  60. _AWS_S3_ENDPOINT_REGEX = re.compile(
  61. _AWS_S3_PREFIX +
  62. r'((?!s3)(?!-)(?!_)[a-z_\d-]{1,63}(?<!-)(?<!_)\.)*'
  63. r'amazonaws\.com(|\.cn)$',
  64. re.IGNORECASE)
  65. _AWS_ELB_ENDPOINT_REGEX = re.compile(
  66. r'^(?!-)(?!_)[a-z_\d-]{1,63}(?<!-)(?<!_)\.'
  67. r'(?!-)(?!_)[a-z_\d-]{1,63}(?<!-)(?<!_)\.'
  68. r'elb\.amazonaws\.com$',
  69. re.IGNORECASE)
  70. _AWS_S3_PREFIX_REGEX = re.compile(_AWS_S3_PREFIX, re.IGNORECASE)
  71. _REGION_REGEX = re.compile(r'^((?!_)(?!-)[a-z_\d-]{1,63}(?<!-)(?<!_))$',
  72. re.IGNORECASE)
  73. DictType = Dict[str, Union[str, List[str], Tuple[str]]]
  74. def quote(
  75. resource: str,
  76. safe: str = "/",
  77. encoding: Optional[str] = None,
  78. errors: Optional[str] = None,
  79. ) -> str:
  80. """
  81. Wrapper to urllib.parse.quote() replacing back to '~' for older python
  82. versions.
  83. """
  84. return urllib.parse.quote(
  85. resource,
  86. safe=safe,
  87. encoding=encoding,
  88. errors=errors,
  89. ).replace("%7E", "~")
  90. def queryencode(
  91. query: str,
  92. safe: str = "",
  93. encoding: Optional[str] = None,
  94. errors: Optional[str] = None,
  95. ) -> str:
  96. """Encode query parameter value."""
  97. return quote(query, safe, encoding, errors)
  98. def headers_to_strings(
  99. headers: Mapping[str, str | list[str] | tuple[str]],
  100. titled_key: bool = False,
  101. ) -> str:
  102. """Convert HTTP headers to multi-line string."""
  103. values = []
  104. for key, value in headers.items():
  105. key = key.title() if titled_key else key
  106. for item in value if isinstance(value, (list, tuple)) else [value]:
  107. item = re.sub(
  108. r"Credential=([^/]+)",
  109. "Credential=*REDACTED*",
  110. re.sub(r"Signature=([0-9a-f]+)", "Signature=*REDACTED*", item),
  111. ) if titled_key else item
  112. values.append(f"{key}: {item}")
  113. return "\n".join(values)
  114. def _validate_sizes(object_size: int, part_size: int):
  115. """Validate object and part size."""
  116. if part_size > 0:
  117. if part_size < MIN_PART_SIZE:
  118. raise ValueError(
  119. f"part size {part_size} is not supported; minimum allowed 5MiB"
  120. )
  121. if part_size > MAX_PART_SIZE:
  122. raise ValueError(
  123. f"part size {part_size} is not supported; maximum allowed 5GiB"
  124. )
  125. if object_size >= 0:
  126. if object_size > MAX_MULTIPART_OBJECT_SIZE:
  127. raise ValueError(
  128. f"object size {object_size} is not supported; "
  129. f"maximum allowed 5TiB"
  130. )
  131. elif part_size <= 0:
  132. raise ValueError(
  133. "valid part size must be provided when object size is unknown",
  134. )
  135. def _get_part_info(object_size: int, part_size: int):
  136. """Compute part information for object and part size."""
  137. _validate_sizes(object_size, part_size)
  138. if object_size < 0:
  139. return part_size, -1
  140. if part_size > 0:
  141. part_size = min(part_size, object_size)
  142. return part_size, math.ceil(object_size / part_size) if part_size else 1
  143. part_size = math.ceil(
  144. math.ceil(object_size / MAX_MULTIPART_COUNT) / MIN_PART_SIZE,
  145. ) * MIN_PART_SIZE
  146. return part_size, math.ceil(object_size / part_size) if part_size else 1
  147. def get_part_info(object_size: int, part_size: int) -> tuple[int, int]:
  148. """Compute part information for object and part size."""
  149. part_size, part_count = _get_part_info(object_size, part_size)
  150. if part_count > MAX_MULTIPART_COUNT:
  151. raise ValueError(
  152. f"object size {object_size} and part size {part_size} "
  153. f"make more than {MAX_MULTIPART_COUNT} parts for upload"
  154. )
  155. return part_size, part_count
  156. class ProgressType(Protocol):
  157. """typing stub for Put/Get object progress."""
  158. def set_meta(self, object_name: str, total_length: int):
  159. """Set process meta information."""
  160. def update(self, length: int):
  161. """Set current progress length."""
  162. def read_part_data(
  163. stream: BinaryIO,
  164. size: int,
  165. part_data: bytes = b"",
  166. progress: Optional[ProgressType] = None,
  167. ) -> bytes:
  168. """Read part data of given size from stream."""
  169. size -= len(part_data)
  170. while size:
  171. data = stream.read(size)
  172. if not data:
  173. break # EOF reached
  174. if not isinstance(data, bytes):
  175. raise ValueError("read() must return 'bytes' object")
  176. part_data += data
  177. size -= len(data)
  178. if progress:
  179. progress.update(len(data))
  180. return part_data
  181. def makedirs(path: str):
  182. """Wrapper of os.makedirs() ignores errno.EEXIST."""
  183. try:
  184. if path:
  185. os.makedirs(path)
  186. except OSError as exc: # Python >2.5
  187. if exc.errno != errno.EEXIST:
  188. raise
  189. if not os.path.isdir(path):
  190. raise ValueError(f"path {path} is not a directory") from exc
  191. def check_bucket_name(
  192. bucket_name: str,
  193. strict: bool = False,
  194. s3_check: bool = False,
  195. ):
  196. """Check whether bucket name is valid optional with strict check or not."""
  197. if strict:
  198. if not _BUCKET_NAME_REGEX.match(bucket_name):
  199. raise ValueError(f'invalid bucket name {bucket_name}')
  200. else:
  201. if not _OLD_BUCKET_NAME_REGEX.match(bucket_name):
  202. raise ValueError(f'invalid bucket name {bucket_name}')
  203. if _IPV4_REGEX.match(bucket_name):
  204. raise ValueError(f'bucket name {bucket_name} must not be formatted '
  205. 'as an IP address')
  206. unallowed_successive_chars = ['..', '.-', '-.']
  207. if any(x in bucket_name for x in unallowed_successive_chars):
  208. raise ValueError(f'bucket name {bucket_name} contains invalid '
  209. 'successive characters')
  210. if (
  211. s3_check and
  212. bucket_name.startswith("xn--") or
  213. bucket_name.endswith("-s3alias") or
  214. bucket_name.endswith("--ol-s3")
  215. ):
  216. raise ValueError(f"bucket name {bucket_name} must not start with "
  217. "'xn--' and must not end with '--s3alias' or "
  218. "'--ol-s3'")
  219. def check_non_empty_string(string: str | bytes):
  220. """Check whether given string is not empty."""
  221. try:
  222. if not string.strip():
  223. raise ValueError()
  224. except AttributeError as exc:
  225. raise TypeError() from exc
  226. def check_object_name(object_name: str):
  227. """Check whether given object name is valid."""
  228. check_non_empty_string(object_name)
  229. tokens = object_name.split("/")
  230. if "." in tokens or ".." in tokens:
  231. raise ValueError(
  232. "object name with '.' or '..' path segment is not supported",
  233. )
  234. def is_valid_policy_type(policy: str | bytes):
  235. """
  236. Validate if policy is type str
  237. :param policy: S3 style Bucket policy.
  238. :return: True if policy parameter is of a valid type, 'string'.
  239. Raise :exc:`TypeError` otherwise.
  240. """
  241. if not isinstance(policy, (str, bytes)):
  242. raise TypeError("policy must be str or bytes type")
  243. check_non_empty_string(policy)
  244. return True
  245. def check_ssec(sse: Optional[SseCustomerKey]):
  246. """Check sse is SseCustomerKey type or not."""
  247. if sse and not isinstance(sse, SseCustomerKey):
  248. raise ValueError("SseCustomerKey type is required")
  249. def check_sse(sse: Optional[Sse]):
  250. """Check sse is Sse type or not."""
  251. if sse and not isinstance(sse, Sse):
  252. raise ValueError("Sse type is required")
  253. def md5sum_hash(data: Optional[str | bytes]) -> Optional[str]:
  254. """Compute MD5 of data and return hash as Base64 encoded value."""
  255. if data is None:
  256. return None
  257. # indicate md5 hashing algorithm is not used in a security context.
  258. # Refer https://bugs.python.org/issue9216 for more information.
  259. hasher = hashlib.new( # type: ignore[call-arg]
  260. "md5",
  261. usedforsecurity=False,
  262. )
  263. hasher.update(data.encode() if isinstance(data, str) else data)
  264. md5sum = base64.b64encode(hasher.digest())
  265. return md5sum.decode() if isinstance(md5sum, bytes) else md5sum
  266. def sha256_hash(data: Optional[str | bytes]) -> str:
  267. """Compute SHA-256 of data and return hash as hex encoded value."""
  268. data = data or b""
  269. hasher = hashlib.sha256()
  270. hasher.update(data.encode() if isinstance(data, str) else data)
  271. sha256sum = hasher.hexdigest()
  272. if isinstance(sha256sum, bytes):
  273. return sha256sum.decode()
  274. return sha256sum
  275. def url_replace(
  276. *,
  277. url: urllib.parse.SplitResult,
  278. scheme: Optional[str] = None,
  279. netloc: Optional[str] = None,
  280. path: Optional[str] = None,
  281. query: Optional[str] = None,
  282. fragment: Optional[str] = None,
  283. ) -> urllib.parse.SplitResult:
  284. """Return new URL with replaced properties in given URL."""
  285. return urllib.parse.SplitResult(
  286. scheme if scheme is not None else url.scheme,
  287. netloc if netloc is not None else url.netloc,
  288. path if path is not None else url.path,
  289. query if query is not None else url.query,
  290. fragment if fragment is not None else url.fragment,
  291. )
  292. def _metadata_to_headers(metadata: DictType) -> dict[str, list[str]]:
  293. """Convert user metadata to headers."""
  294. def normalize_key(key: str) -> str:
  295. if not key.lower().startswith("x-amz-meta-"):
  296. key = "X-Amz-Meta-" + key
  297. return key
  298. def to_string(value) -> str:
  299. value = str(value)
  300. try:
  301. value.encode("us-ascii")
  302. except UnicodeEncodeError as exc:
  303. raise ValueError(
  304. f"unsupported metadata value {value}; "
  305. f"only US-ASCII encoded characters are supported"
  306. ) from exc
  307. return value
  308. def normalize_value(values: str | list[str] | tuple[str]) -> list[str]:
  309. if not isinstance(values, (list, tuple)):
  310. values = [values]
  311. return [to_string(value) for value in values]
  312. return {
  313. normalize_key(key): normalize_value(value)
  314. for key, value in (metadata or {}).items()
  315. }
  316. def normalize_headers(headers: Optional[DictType]) -> DictType:
  317. """Normalize headers by prefixing 'X-Amz-Meta-' for user metadata."""
  318. headers = {str(key): value for key, value in (headers or {}).items()}
  319. def guess_user_metadata(key: str) -> bool:
  320. key = key.lower()
  321. return not (
  322. key.startswith("x-amz-") or
  323. key in [
  324. "cache-control",
  325. "content-encoding",
  326. "content-type",
  327. "content-disposition",
  328. "content-language",
  329. ]
  330. )
  331. user_metadata = {
  332. key: value for key, value in headers.items()
  333. if guess_user_metadata(key)
  334. }
  335. # Remove guessed user metadata.
  336. _ = [headers.pop(key) for key in user_metadata]
  337. headers.update(_metadata_to_headers(user_metadata))
  338. return headers
  339. def genheaders(
  340. headers: Optional[DictType],
  341. sse: Optional[Sse],
  342. tags: Optional[dict[str, str]],
  343. retention,
  344. legal_hold: bool,
  345. ) -> DictType:
  346. """Generate headers for given parameters."""
  347. headers = normalize_headers(headers)
  348. headers.update(sse.headers() if sse else {})
  349. tagging = "&".join(
  350. [
  351. queryencode(key) + "=" + queryencode(value)
  352. for key, value in (tags or {}).items()
  353. ],
  354. )
  355. if tagging:
  356. headers["x-amz-tagging"] = tagging
  357. if retention and retention.mode:
  358. headers["x-amz-object-lock-mode"] = retention.mode
  359. headers["x-amz-object-lock-retain-until-date"] = (
  360. to_iso8601utc(retention.retain_until_date) or ""
  361. )
  362. if legal_hold:
  363. headers["x-amz-object-lock-legal-hold"] = "ON"
  364. return headers
  365. def _get_aws_info(
  366. host: str,
  367. https: bool,
  368. region: Optional[str],
  369. ) -> tuple[Optional[dict], Optional[str]]:
  370. """Extract AWS domain information. """
  371. if not _HOSTNAME_REGEX.match(host):
  372. return (None, None)
  373. if _AWS_ELB_ENDPOINT_REGEX.match(host):
  374. region_in_host = host.split(".elb.amazonaws.com", 1)[0].split(".")[-1]
  375. return (None, region or region_in_host)
  376. if not _AWS_ENDPOINT_REGEX.match(host):
  377. return (None, None)
  378. if host.startswith("ec2-"):
  379. return (None, None)
  380. if not _AWS_S3_ENDPOINT_REGEX.match(host):
  381. raise ValueError(f"invalid Amazon AWS host {host}")
  382. matcher = _AWS_S3_PREFIX_REGEX.match(host)
  383. end = matcher.end() if matcher else 0
  384. aws_s3_prefix = host[:end]
  385. if "s3-accesspoint" in aws_s3_prefix and not https:
  386. raise ValueError(f"use HTTPS scheme for host {host}")
  387. tokens = host[end:].split(".")
  388. dualstack = tokens[0] == "dualstack"
  389. if dualstack:
  390. tokens = tokens[1:]
  391. region_in_host = ""
  392. if tokens[0] not in ["vpce", "amazonaws"]:
  393. region_in_host = tokens[0]
  394. tokens = tokens[1:]
  395. aws_domain_suffix = ".".join(tokens)
  396. if host in "s3-external-1.amazonaws.com":
  397. region_in_host = "us-east-1"
  398. if host in ["s3-us-gov-west-1.amazonaws.com",
  399. "s3-fips-us-gov-west-1.amazonaws.com"]:
  400. region_in_host = "us-gov-west-1"
  401. if (aws_domain_suffix.endswith(".cn") and
  402. not aws_s3_prefix.endswith("s3-accelerate.") and
  403. not region_in_host and
  404. not region):
  405. raise ValueError(
  406. f"region missing in Amazon S3 China endpoint {host}",
  407. )
  408. return ({"s3_prefix": aws_s3_prefix,
  409. "domain_suffix": aws_domain_suffix,
  410. "region": region or region_in_host,
  411. "dualstack": dualstack}, None)
  412. def _parse_url(endpoint: str) -> urllib.parse.SplitResult:
  413. """Parse url string."""
  414. url = urllib.parse.urlsplit(endpoint)
  415. host = url.hostname
  416. if url.scheme.lower() not in ["http", "https"]:
  417. raise ValueError("scheme in endpoint must be http or https")
  418. url = url_replace(url=url, scheme=url.scheme.lower())
  419. if url.path and url.path != "/":
  420. raise ValueError("path in endpoint is not allowed")
  421. url = url_replace(url=url, path="")
  422. if url.query:
  423. raise ValueError("query in endpoint is not allowed")
  424. if url.fragment:
  425. raise ValueError("fragment in endpoint is not allowed")
  426. try:
  427. url.port
  428. except ValueError as exc:
  429. raise ValueError("invalid port") from exc
  430. if url.username:
  431. raise ValueError("username in endpoint is not allowed")
  432. if url.password:
  433. raise ValueError("password in endpoint is not allowed")
  434. if (
  435. (url.scheme == "http" and url.port == 80) or
  436. (url.scheme == "https" and url.port == 443)
  437. ):
  438. url = url_replace(url=url, netloc=host)
  439. return url
  440. class BaseURL:
  441. """Base URL of S3 endpoint."""
  442. _aws_info: Optional[dict]
  443. _virtual_style_flag: bool
  444. _url: urllib.parse.SplitResult
  445. _region: Optional[str]
  446. _accelerate_host_flag: bool
  447. def __init__(self, endpoint: str, region: Optional[str]):
  448. url = _parse_url(endpoint)
  449. if region and not _REGION_REGEX.match(region):
  450. raise ValueError(f"invalid region {region}")
  451. hostname = url.hostname or ""
  452. self._aws_info, region_in_host = _get_aws_info(
  453. hostname, url.scheme == "https", region)
  454. self._virtual_style_flag = (
  455. self._aws_info is not None or hostname.endswith("aliyuncs.com")
  456. )
  457. self._url = url
  458. self._region = region or region_in_host
  459. self._accelerate_host_flag = False
  460. if self._aws_info:
  461. self._region = self._aws_info["region"]
  462. self._accelerate_host_flag = (
  463. self._aws_info["s3_prefix"].endswith("s3-accelerate.")
  464. )
  465. @property
  466. def region(self) -> Optional[str]:
  467. """Get region."""
  468. return self._region
  469. @property
  470. def is_https(self) -> bool:
  471. """Check if scheme is HTTPS."""
  472. return self._url.scheme == "https"
  473. @property
  474. def host(self) -> str:
  475. """Get hostname."""
  476. return self._url.netloc
  477. @property
  478. def is_aws_host(self) -> bool:
  479. """Check if URL points to AWS host."""
  480. return self._aws_info is not None
  481. @property
  482. def aws_s3_prefix(self) -> Optional[str]:
  483. """Get AWS S3 domain prefix."""
  484. return self._aws_info["s3_prefix"] if self._aws_info else None
  485. @aws_s3_prefix.setter
  486. def aws_s3_prefix(self, s3_prefix: str):
  487. """Set AWS s3 domain prefix."""
  488. if not _AWS_S3_PREFIX_REGEX.match(s3_prefix):
  489. raise ValueError(f"invalid AWS S3 domain prefix {s3_prefix}")
  490. if self._aws_info:
  491. self._aws_info["s3_prefix"] = s3_prefix
  492. @property
  493. def accelerate_host_flag(self) -> bool:
  494. """Get AWS accelerate host flag."""
  495. return self._accelerate_host_flag
  496. @accelerate_host_flag.setter
  497. def accelerate_host_flag(self, flag: bool):
  498. """Set AWS accelerate host flag."""
  499. self._accelerate_host_flag = flag
  500. @property
  501. def dualstack_host_flag(self) -> bool:
  502. """Check if URL points to AWS dualstack host."""
  503. return self._aws_info["dualstack"] if self._aws_info else False
  504. @dualstack_host_flag.setter
  505. def dualstack_host_flag(self, flag: bool):
  506. """Set AWS dualstack host."""
  507. if self._aws_info:
  508. self._aws_info["dualstack"] = flag
  509. @property
  510. def virtual_style_flag(self) -> bool:
  511. """Check to use virtual style or not."""
  512. return self._virtual_style_flag
  513. @virtual_style_flag.setter
  514. def virtual_style_flag(self, flag: bool):
  515. """Check to use virtual style or not."""
  516. self._virtual_style_flag = flag
  517. @classmethod
  518. def _build_aws_url(
  519. cls,
  520. *,
  521. aws_info: dict,
  522. url: urllib.parse.SplitResult,
  523. bucket_name: Optional[str],
  524. enforce_path_style: bool,
  525. region: str,
  526. ) -> urllib.parse.SplitResult:
  527. """Build URL for given information."""
  528. s3_prefix = aws_info["s3_prefix"]
  529. domain_suffix = aws_info["domain_suffix"]
  530. host = f"{s3_prefix}{domain_suffix}"
  531. if host in ["s3-external-1.amazonaws.com",
  532. "s3-us-gov-west-1.amazonaws.com",
  533. "s3-fips-us-gov-west-1.amazonaws.com"]:
  534. return url_replace(url=url, netloc=host)
  535. netloc = s3_prefix
  536. if "s3-accelerate" in s3_prefix:
  537. if "." in (bucket_name or ""):
  538. raise ValueError(
  539. f"bucket name '{bucket_name}' with '.' is not allowed "
  540. f"for accelerate endpoint"
  541. )
  542. if enforce_path_style:
  543. netloc = netloc.replace("-accelerate", "", 1)
  544. if aws_info["dualstack"]:
  545. netloc += "dualstack."
  546. if "s3-accelerate" not in s3_prefix:
  547. netloc += region + "."
  548. netloc += domain_suffix
  549. return url_replace(url=url, netloc=netloc)
  550. def _build_list_buckets_url(
  551. self,
  552. url: urllib.parse.SplitResult,
  553. region: Optional[str],
  554. ) -> urllib.parse.SplitResult:
  555. """Build URL for ListBuckets API."""
  556. if not self._aws_info:
  557. return url
  558. s3_prefix = self._aws_info["s3_prefix"]
  559. domain_suffix = self._aws_info["domain_suffix"]
  560. host = f"{s3_prefix}{domain_suffix}"
  561. if host in ["s3-external-1.amazonaws.com",
  562. "s3-us-gov-west-1.amazonaws.com",
  563. "s3-fips-us-gov-west-1.amazonaws.com"]:
  564. return url_replace(url=url, netloc=host)
  565. if s3_prefix.startswith("s3.") or s3_prefix.startswith("s3-"):
  566. s3_prefix = "s3."
  567. cn_suffix = ".cn" if domain_suffix.endswith(".cn") else ""
  568. domain_suffix = f"amazonaws.com{cn_suffix}"
  569. return url_replace(
  570. url=url,
  571. netloc=f"{s3_prefix}{region}.{domain_suffix}",
  572. )
  573. def build(
  574. self,
  575. *,
  576. method: str,
  577. region: str,
  578. bucket_name: Optional[str] = None,
  579. object_name: Optional[str] = None,
  580. query_params: Optional[DictType] = None,
  581. ) -> urllib.parse.SplitResult:
  582. """Build URL for given information."""
  583. if not bucket_name and object_name:
  584. raise ValueError(
  585. f"empty bucket name for object name {object_name}",
  586. )
  587. url = url_replace(url=self._url, path="/")
  588. query = []
  589. for key, values in sorted((query_params or {}).items()):
  590. values = values if isinstance(values, (list, tuple)) else [values]
  591. query += [
  592. f"{queryencode(key)}={queryencode(value)}"
  593. for value in sorted(values)
  594. ]
  595. url = url_replace(url=url, query="&".join(query))
  596. if not bucket_name:
  597. return self._build_list_buckets_url(url, region)
  598. enforce_path_style = (
  599. # CreateBucket API requires path style in Amazon AWS S3.
  600. (method == "PUT" and not object_name and not query_params) or
  601. # GetBucketLocation API requires path style in Amazon AWS S3.
  602. (query_params and "location" in query_params) or
  603. # Use path style for bucket name containing '.' which causes
  604. # SSL certificate validation error.
  605. ("." in bucket_name and self._url.scheme == "https")
  606. )
  607. if self._aws_info:
  608. url = BaseURL._build_aws_url(
  609. aws_info=self._aws_info,
  610. url=url,
  611. bucket_name=bucket_name,
  612. enforce_path_style=enforce_path_style,
  613. region=region,
  614. )
  615. netloc = url.netloc
  616. path = "/"
  617. if enforce_path_style or not self._virtual_style_flag:
  618. path = f"/{bucket_name}"
  619. else:
  620. netloc = f"{bucket_name}.{netloc}"
  621. if object_name:
  622. path += ("" if path.endswith("/") else "/") + quote(object_name)
  623. return url_replace(url=url, netloc=netloc, path=path)
  624. @dataclass(frozen=True)
  625. class ObjectWriteResult:
  626. """Result class of any APIs doing object creation."""
  627. bucket_name: str
  628. object_name: str
  629. version_id: Optional[str]
  630. etag: Optional[str]
  631. http_headers: HTTPHeaderDict
  632. last_modified: Optional[datetime] = None
  633. location: Optional[str] = None
  634. class Worker(Thread):
  635. """ Thread executing tasks from a given tasks queue """
  636. def __init__(
  637. self,
  638. tasks_queue: Queue,
  639. results_queue: Queue,
  640. exceptions_queue: Queue,
  641. ):
  642. Thread.__init__(self, daemon=True)
  643. self._tasks_queue = tasks_queue
  644. self._results_queue = results_queue
  645. self._exceptions_queue = exceptions_queue
  646. self.start()
  647. def run(self):
  648. """ Continuously receive tasks and execute them """
  649. while True:
  650. task = self._tasks_queue.get()
  651. if not task:
  652. self._tasks_queue.task_done()
  653. break
  654. func, args, kargs, cleanup_func = task
  655. # No exception detected in any thread,
  656. # continue the execution.
  657. if self._exceptions_queue.empty():
  658. try:
  659. result = func(*args, **kargs)
  660. self._results_queue.put(result)
  661. except Exception as ex: # pylint: disable=broad-except
  662. self._exceptions_queue.put(ex)
  663. # call cleanup i.e. Semaphore.release irrespective of task
  664. # execution to avoid race condition.
  665. cleanup_func()
  666. # Mark this task as done, whether an exception happened or not
  667. self._tasks_queue.task_done()
  668. class ThreadPool:
  669. """ Pool of threads consuming tasks from a queue """
  670. _results_queue: Queue
  671. _exceptions_queue: Queue
  672. _tasks_queue: Queue
  673. _sem: BoundedSemaphore
  674. _num_threads: int
  675. def __init__(self, num_threads: int):
  676. self._results_queue = Queue()
  677. self._exceptions_queue = Queue()
  678. self._tasks_queue = Queue()
  679. self._sem = BoundedSemaphore(num_threads)
  680. self._num_threads = num_threads
  681. def add_task(self, func, *args, **kargs):
  682. """
  683. Add a task to the queue. Calling this function can block
  684. until workers have a room for processing new tasks. Blocking
  685. the caller also prevents the latter from allocating a lot of
  686. memory while workers are still busy running their assigned tasks.
  687. """
  688. self._sem.acquire() # pylint: disable=consider-using-with
  689. cleanup_func = self._sem.release
  690. self._tasks_queue.put((func, args, kargs, cleanup_func))
  691. def start_parallel(self):
  692. """ Prepare threads to run tasks"""
  693. for _ in range(self._num_threads):
  694. Worker(
  695. self._tasks_queue, self._results_queue, self._exceptions_queue,
  696. )
  697. def result(self) -> Queue:
  698. """ Stop threads and return the result of all called tasks """
  699. # Send None to all threads to cleanly stop them
  700. for _ in range(self._num_threads):
  701. self._tasks_queue.put(None)
  702. # Wait for completion of all the tasks in the queue
  703. self._tasks_queue.join()
  704. # Check if one of the thread raised an exception, if yes
  705. # raise it here in the function
  706. if not self._exceptions_queue.empty():
  707. raise self._exceptions_queue.get()
  708. return self._results_queue