Coverage for python/lsst/daf/butler/core/_butlerUri/s3.py : 78%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22from __future__ import annotations
24import logging
25import re
26import tempfile
28__all__ = ('ButlerS3URI',)
30from typing import (
31 TYPE_CHECKING,
32 Optional,
33 Any,
34 Callable,
35 Iterator,
36 List,
37 Tuple,
38 Union,
39)
41from .utils import NoTransaction
42from ._butlerUri import ButlerURI
43from .s3utils import getS3Client, s3CheckFileExists, bucketExists
45from botocore.exceptions import ClientError
46from http.client import ImproperConnectionState, HTTPException
47from urllib3.exceptions import RequestError, HTTPError
49if TYPE_CHECKING: 49 ↛ 50line 49 didn't jump to line 50, because the condition on line 49 was never true
50 try:
51 import boto3
52 except ImportError:
53 pass
54 from ..datastore import DatastoreTransaction
56# https://pypi.org/project/backoff/
57try:
58 import backoff
59except ImportError:
60 class Backoff():
61 @staticmethod
62 def expo(func: Callable, *args: Any, **kwargs: Any) -> Callable:
63 return func
65 @staticmethod
66 def on_exception(func: Callable, *args: Any, **kwargs: Any) -> Callable:
67 return func
69 backoff = Backoff
71# settings for "backoff" retry decorators. these retries are belt-and-
72# suspenders along with the retries built into Boto3, to account for
73# semantic differences in errors between S3-like providers.
74retryable_io_errors = (
75 # http.client
76 ImproperConnectionState, HTTPException,
77 # urllib3.exceptions
78 RequestError, HTTPError,
79 # built-ins
80 TimeoutError, ConnectionError)
81retryable_client_errors = (
82 # botocore.exceptions
83 ClientError,
84 # built-ins
85 PermissionError)
86all_retryable_errors = retryable_client_errors + retryable_io_errors
87max_retry_time = 60
90log = logging.getLogger(__name__)
93class ButlerS3URI(ButlerURI):
94 """S3 URI implementation class."""
96 @property
97 def client(self) -> boto3.client:
98 """Client object to address remote resource."""
99 # Defer import for circular dependencies
100 return getS3Client()
102 @backoff.on_exception(backoff.expo, retryable_client_errors, max_time=max_retry_time)
103 def exists(self) -> bool:
104 """Check that the S3 resource exists."""
105 if self.is_root: 105 ↛ 107line 105 didn't jump to line 107, because the condition on line 105 was never true
106 # Only check for the bucket since the path is irrelevant
107 return bucketExists(self.netloc)
108 exists, _ = s3CheckFileExists(self, client=self.client)
109 return exists
111 @backoff.on_exception(backoff.expo, retryable_client_errors, max_time=max_retry_time)
112 def size(self) -> int:
113 """Return the size of the resource in bytes."""
114 if self.dirLike: 114 ↛ 115line 114 didn't jump to line 115, because the condition on line 114 was never true
115 return 0
116 _, sz = s3CheckFileExists(self, client=self.client)
117 return sz
119 @backoff.on_exception(backoff.expo, retryable_client_errors, max_time=max_retry_time)
120 def remove(self) -> None:
121 """Remove the resource."""
122 # https://github.com/boto/boto3/issues/507 - there is no
123 # way of knowing if the file was actually deleted except
124 # for checking all the keys again, reponse is HTTP 204 OK
125 # response all the time
126 self.client.delete_object(Bucket=self.netloc, Key=self.relativeToPathRoot)
128 @backoff.on_exception(backoff.expo, all_retryable_errors, max_time=max_retry_time)
129 def read(self, size: int = -1) -> bytes:
130 """Read the contents of the resource."""
131 args = {}
132 if size > 0:
133 args["Range"] = f"bytes=0-{size-1}"
134 try:
135 response = self.client.get_object(Bucket=self.netloc,
136 Key=self.relativeToPathRoot,
137 **args)
138 except (self.client.exceptions.NoSuchKey, self.client.exceptions.NoSuchBucket) as err:
139 raise FileNotFoundError(f"No such resource: {self}") from err
140 body = response["Body"].read()
141 response["Body"].close()
142 return body
144 @backoff.on_exception(backoff.expo, all_retryable_errors, max_time=max_retry_time)
145 def write(self, data: bytes, overwrite: bool = True) -> None:
146 """Write the supplied data to the resource."""
147 if not overwrite:
148 if self.exists(): 148 ↛ 149line 148 didn't jump to line 149, because the condition on line 148 was never true
149 raise FileExistsError(f"Remote resource {self} exists and overwrite has been disabled")
150 self.client.put_object(Bucket=self.netloc, Key=self.relativeToPathRoot,
151 Body=data)
153 @backoff.on_exception(backoff.expo, all_retryable_errors, max_time=max_retry_time)
154 def mkdir(self) -> None:
155 """Write a directory key to S3."""
156 if not bucketExists(self.netloc): 156 ↛ 157line 156 didn't jump to line 157, because the condition on line 156 was never true
157 raise ValueError(f"Bucket {self.netloc} does not exist for {self}!")
159 if not self.dirLike: 159 ↛ 160line 159 didn't jump to line 160, because the condition on line 159 was never true
160 raise ValueError(f"Can not create a 'directory' for file-like URI {self}")
162 # don't create S3 key when root is at the top-level of an Bucket
163 if not self.path == "/": 163 ↛ exitline 163 didn't return from function 'mkdir', because the condition on line 163 was never false
164 self.client.put_object(Bucket=self.netloc, Key=self.relativeToPathRoot)
166 @backoff.on_exception(backoff.expo, all_retryable_errors, max_time=max_retry_time)
167 def _as_local(self) -> Tuple[str, bool]:
168 """Download object from S3 and place in temporary directory.
170 Returns
171 -------
172 path : `str`
173 Path to local temporary file.
174 temporary : `bool`
175 Always returns `True`. This is always a temporary file.
176 """
177 with tempfile.NamedTemporaryFile(suffix=self.getExtension(), delete=False) as tmpFile:
178 self.client.download_fileobj(self.netloc, self.relativeToPathRoot, tmpFile)
179 return tmpFile.name, True
181 @backoff.on_exception(backoff.expo, all_retryable_errors, max_time=max_retry_time)
182 def transfer_from(self, src: ButlerURI, transfer: str = "copy",
183 overwrite: bool = False,
184 transaction: Optional[Union[DatastoreTransaction, NoTransaction]] = None) -> None:
185 """Transfer the current resource to an S3 bucket.
187 Parameters
188 ----------
189 src : `ButlerURI`
190 Source URI.
191 transfer : `str`
192 Mode to use for transferring the resource. Supports the following
193 options: copy.
194 overwrite : `bool`, optional
195 Allow an existing file to be overwritten. Defaults to `False`.
196 transaction : `DatastoreTransaction`, optional
197 Currently unused.
198 """
199 # Fail early to prevent delays if remote resources are requested
200 if transfer not in self.transferModes:
201 raise ValueError(f"Transfer mode '{transfer}' not supported by URI scheme {self.scheme}")
203 log.debug(f"Transferring {src} [exists: {src.exists()}] -> "
204 f"{self} [exists: {self.exists()}] (transfer={transfer})")
206 if not overwrite and self.exists():
207 raise FileExistsError(f"Destination path '{self}' already exists.")
209 if transfer == "auto": 209 ↛ 210line 209 didn't jump to line 210, because the condition on line 209 was never true
210 transfer = self.transferDefault
212 if isinstance(src, type(self)):
213 # Looks like an S3 remote uri so we can use direct copy
214 # note that boto3.resource.meta.copy is cleverer than the low
215 # level copy_object
216 copy_source = {
217 "Bucket": src.netloc,
218 "Key": src.relativeToPathRoot,
219 }
220 self.client.copy_object(CopySource=copy_source, Bucket=self.netloc, Key=self.relativeToPathRoot)
221 else:
222 # Use local file and upload it
223 with src.as_local() as local_uri:
225 # resource.meta.upload_file seems like the right thing
226 # but we have a low level client
227 with open(local_uri.ospath, "rb") as fh:
228 self.client.put_object(Bucket=self.netloc,
229 Key=self.relativeToPathRoot, Body=fh)
231 # This was an explicit move requested from a remote resource
232 # try to remove that resource
233 if transfer == "move": 233 ↛ 235line 233 didn't jump to line 235, because the condition on line 233 was never true
234 # Transactions do not work here
235 src.remove()
237 @backoff.on_exception(backoff.expo, all_retryable_errors, max_time=max_retry_time)
238 def walk(self, file_filter: Optional[Union[str, re.Pattern]] = None) -> Iterator[Union[List,
239 Tuple[ButlerURI,
240 List[str],
241 List[str]]]]:
242 """Walk the directory tree returning matching files and directories.
244 Parameters
245 ----------
246 file_filter : `str` or `re.Pattern`, optional
247 Regex to filter out files from the list before it is returned.
249 Yields
250 ------
251 dirpath : `ButlerURI`
252 Current directory being examined.
253 dirnames : `list` of `str`
254 Names of subdirectories within dirpath.
255 filenames : `list` of `str`
256 Names of all the files within dirpath.
257 """
258 # We pretend that S3 uses directories and files and not simply keys
259 if not (self.isdir() or self.is_root): 259 ↛ 260line 259 didn't jump to line 260, because the condition on line 259 was never true
260 raise ValueError(f"Can not walk a non-directory URI: {self}")
262 if isinstance(file_filter, str): 262 ↛ 263line 262 didn't jump to line 263, because the condition on line 262 was never true
263 file_filter = re.compile(file_filter)
265 s3_paginator = self.client.get_paginator('list_objects_v2')
267 # Limit each query to a single "directory" to match os.walk
268 # We could download all keys at once with no delimiter and work
269 # it out locally but this could potentially lead to large memory
270 # usage for millions of keys. It will also make the initial call
271 # to this method potentially very slow. If making this method look
272 # like os.walk was not required, we could query all keys with
273 # pagination and return them in groups of 1000, but that would
274 # be a different interface since we can't guarantee we would get
275 # them all grouped properly across the 1000 limit boundary.
276 prefix = self.relativeToPathRoot if not self.is_root else ""
277 prefix_len = len(prefix)
278 dirnames = []
279 filenames = []
280 files_there = False
282 for page in s3_paginator.paginate(Bucket=self.netloc, Prefix=prefix, Delimiter="/"):
283 # All results are returned as full key names and we must
284 # convert them back to the root form. The prefix is fixed
285 # and delimited so that is a simple trim
287 # Directories are reported in the CommonPrefixes result
288 # which reports the entire key and must be stripped.
289 found_dirs = [dir["Prefix"][prefix_len:] for dir in page.get("CommonPrefixes", ())]
290 dirnames.extend(found_dirs)
292 found_files = [file["Key"][prefix_len:] for file in page.get("Contents", ())]
293 if found_files:
294 files_there = True
295 if file_filter is not None:
296 found_files = [f for f in found_files if file_filter.search(f)]
298 filenames.extend(found_files)
300 # Directories do not exist so we can't test for them. If no files
301 # or directories were found though, this means that it effectively
302 # does not exist and we should match os.walk() behavior and return
303 # [].
304 if not dirnames and not files_there: 304 ↛ 305line 304 didn't jump to line 305, because the condition on line 304 was never true
305 yield []
306 else:
307 yield self, dirnames, filenames
309 for dir in dirnames:
310 new_uri = self.join(dir)
311 yield from new_uri.walk(file_filter)