Hide keyboard shortcuts

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/>. 

21 

22from __future__ import annotations 

23 

24"""S3 datastore.""" 

25 

26__all__ = ("S3Datastore", ) 

27 

28import boto3 

29import logging 

30import os 

31import pathlib 

32import tempfile 

33 

34from typing import ( 

35 TYPE_CHECKING, 

36 Any, 

37 Optional, 

38 Type, 

39 Union, 

40) 

41 

42from lsst.daf.butler import ( 

43 ButlerURI, 

44 DatasetRef, 

45 Formatter, 

46 Location, 

47 StoredFileInfo, 

48) 

49 

50from .fileLikeDatastore import FileLikeDatastore 

51from lsst.daf.butler.core.s3utils import s3CheckFileExists, bucketExists 

52 

53if TYPE_CHECKING: 53 ↛ 54line 53 didn't jump to line 54, because the condition on line 53 was never true

54 from .fileLikeDatastore import DatastoreFileGetInformation 

55 from lsst.daf.butler import DatastoreConfig 

56 from lsst.daf.butler.registry.interfaces import DatastoreRegistryBridgeManager 

57 

58log = logging.getLogger(__name__) 

59 

60 

61class S3Datastore(FileLikeDatastore): 

62 """Basic S3 Object Storage backed Datastore. 

63 

64 Parameters 

65 ---------- 

66 config : `DatastoreConfig` or `str` 

67 Configuration. A string should refer to the name of the config file. 

68 bridgeManager : `DatastoreRegistryBridgeManager` 

69 Object that manages the interface between `Registry` and datastores. 

70 butlerRoot : `str`, optional 

71 New datastore root to use to override the configuration value. 

72 

73 Raises 

74 ------ 

75 ValueError 

76 If root location does not exist and ``create`` is `False` in the 

77 configuration. 

78 

79 Notes 

80 ----- 

81 S3Datastore supports non-link transfer modes for file-based ingest: 

82 `"move"`, `"copy"`, and `None` (no transfer). 

83 """ 

84 

85 defaultConfigFile = "datastores/s3Datastore.yaml" 

86 """Path to configuration defaults. Relative to $DAF_BUTLER_DIR/config or 

87 absolute path. Can be None if no defaults specified. 

88 """ 

89 

90 def __init__(self, config: Union[DatastoreConfig, str], 

91 bridgeManager: DatastoreRegistryBridgeManager, butlerRoot: str = None): 

92 super().__init__(config, bridgeManager, butlerRoot) 

93 

94 self.client = boto3.client("s3") 

95 if not bucketExists(self.locationFactory.netloc): 95 ↛ 101line 95 didn't jump to line 101, because the condition on line 95 was never true

96 # PosixDatastore creates the root directory if one does not exist. 

97 # Calling s3 client.create_bucket is possible but also requires 

98 # ACL LocationConstraints, Permissions and other configuration 

99 # parameters, so for now we do not create a bucket if one is 

100 # missing. Further discussion can make this happen though. 

101 raise IOError(f"Bucket {self.locationFactory.netloc} does not exist!") 

102 

103 def _artifact_exists(self, location: Location) -> bool: 

104 """Check that an artifact exists in this datastore at the specified 

105 location. 

106 

107 Parameters 

108 ---------- 

109 location : `Location` 

110 Expected location of the artifact associated with this datastore. 

111 

112 Returns 

113 ------- 

114 exists : `bool` 

115 True if the location can be found, false otherwise. 

116 """ 

117 return s3CheckFileExists(location, client=self.client) 

118 

119 def _delete_artifact(self, location: Location) -> None: 

120 """Delete the artifact from the datastore. 

121 

122 Parameters 

123 ---------- 

124 location : `Location` 

125 Location of the artifact associated with this datastore. 

126 """ 

127 self.client.delete_object(Bucket=location.netloc, Key=location.relativeToPathRoot) 

128 

129 def _read_artifact_into_memory(self, getInfo: DatastoreFileGetInformation, 

130 ref: DatasetRef, isComponent: bool = False) -> Any: 

131 location = getInfo.location 

132 

133 # since we have to make a GET request to S3 anyhow (for download) we 

134 # might as well use the HEADER metadata for size comparison instead. 

135 # s3CheckFileExists would just duplicate GET/LIST charges in this case. 

136 try: 

137 response = self.client.get_object(Bucket=location.netloc, 

138 Key=location.relativeToPathRoot) 

139 except self.client.exceptions.ClientError as err: 

140 errorcode = err.response["ResponseMetadata"]["HTTPStatusCode"] 

141 # head_object returns 404 when object does not exist only when user 

142 # has s3:ListBucket permission. If list permission does not exist a 

143 # 403 is returned. In practical terms this usually means that the 

144 # file does not exist, but it could also mean user lacks GetObject 

145 # permission. It's hard to tell which case is it. 

146 # docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html 

147 # Unit tests right now demand FileExistsError is raised, but this 

148 # should be updated to PermissionError like in s3CheckFileExists. 

149 if errorcode == 403: 

150 raise FileNotFoundError(f"Dataset with Id {ref.id} not accessible at " 

151 f"expected location {location}. Forbidden HEAD " 

152 "operation error occured. Verify s3:ListBucket " 

153 "and s3:GetObject permissions are granted for " 

154 "your IAM user and that file exists. ") from err 

155 if errorcode == 404: 

156 errmsg = f"Dataset with Id {ref.id} does not exists at expected location {location}." 

157 raise FileNotFoundError(errmsg) from err 

158 # other errors are reraised also, but less descriptively 

159 raise err 

160 

161 storedFileInfo = getInfo.info 

162 if response["ContentLength"] != storedFileInfo.file_size: 162 ↛ 163line 162 didn't jump to line 163, because the condition on line 162 was never true

163 raise RuntimeError("Integrity failure in Datastore. Size of file {} ({}) does not" 

164 " match recorded size of {}".format(location.path, response["ContentLength"], 

165 storedFileInfo.file_size)) 

166 

167 # download the data as bytes 

168 serializedDataset = response["Body"].read() 

169 

170 # format the downloaded bytes into appropriate object directly, or via 

171 # tempfile (when formatter does not support to/from/Bytes). This is S3 

172 # equivalent of PosixDatastore formatter.read try-except block. 

173 formatter = getInfo.formatter 

174 try: 

175 result = formatter.fromBytes(serializedDataset, 

176 component=getInfo.component if isComponent else None) 

177 except NotImplementedError: 177 ↛ 185line 177 didn't jump to line 185

178 with tempfile.NamedTemporaryFile(suffix=formatter.extension) as tmpFile: 

179 tmpFile.write(serializedDataset) 

180 # Flush the write. Do not close the file because that 

181 # will delete it. 

182 tmpFile.flush() 

183 formatter._fileDescriptor.location = Location(*os.path.split(tmpFile.name)) 

184 result = formatter.read(component=getInfo.component if isComponent else None) 

185 except Exception as e: 

186 raise ValueError(f"Failure from formatter '{formatter.name()}' for dataset {ref.id}" 

187 f" ({ref.datasetType.name} from {location.uri}): {e}") from e 

188 

189 return self._post_process_get(result, getInfo.readStorageClass, getInfo.assemblerParams, 

190 isComponent=isComponent) 

191 

192 def _write_in_memory_to_artifact(self, inMemoryDataset: Any, ref: DatasetRef) -> StoredFileInfo: 

193 location, formatter = self._prepare_for_put(inMemoryDataset, ref) 

194 

195 # in PosixDatastore a directory can be created by `safeMakeDir`. In S3 

196 # `Keys` instead only look like directories, but are not. We check if 

197 # an *exact* full key already exists before writing instead. The insert 

198 # key operation is equivalent to creating the dir and the file. 

199 location.updateExtension(formatter.extension) 

200 if s3CheckFileExists(location, client=self.client,)[0]: 

201 raise FileExistsError(f"Cannot write file for ref {ref} as " 

202 f"output file {location.uri} exists.") 

203 

204 # upload the file directly from bytes or by using a temporary file if 

205 # _toBytes is not implemented 

206 try: 

207 serializedDataset = formatter.toBytes(inMemoryDataset) 

208 self.client.put_object(Bucket=location.netloc, Key=location.relativeToPathRoot, 

209 Body=serializedDataset) 

210 log.debug("Wrote file directly to %s", location.uri) 

211 except NotImplementedError: 

212 with tempfile.NamedTemporaryFile(suffix=formatter.extension) as tmpFile: 

213 formatter._fileDescriptor.location = Location(*os.path.split(tmpFile.name)) 

214 formatter.write(inMemoryDataset) 

215 self.client.upload_file(Bucket=location.netloc, Key=location.relativeToPathRoot, 

216 Filename=tmpFile.name) 

217 log.debug("Wrote file to %s via a temporary directory.", location.uri) 

218 

219 if self._transaction is None: 219 ↛ 220line 219 didn't jump to line 220, because the condition on line 219 was never true

220 raise RuntimeError("Attempting to write artifact without transaction enabled") 

221 

222 # Register a callback to try to delete the uploaded data if 

223 # the ingest fails below 

224 self._transaction.registerUndo("write", self.client.delete_object, 

225 Bucket=location.netloc, Key=location.relativeToPathRoot) 

226 

227 # URI is needed to resolve what ingest case are we dealing with 

228 return self._extractIngestInfo(location.uri, ref, formatter=formatter) 

229 

230 def _overrideTransferMode(self, *datasets: Any, transfer: Optional[str] = None) -> Optional[str]: 

231 # Docstring inherited from base class 

232 if transfer != "auto": 232 ↛ 234line 232 didn't jump to line 234, because the condition on line 232 was never false

233 return transfer 

234 return "copy" 

235 

236 def _standardizeIngestPath(self, path: str, *, transfer: Optional[str] = None) -> str: 

237 # Docstring inherited from FileLikeDatastore._standardizeIngestPath. 

238 if transfer not in (None, "move", "copy"): 238 ↛ 239line 238 didn't jump to line 239, because the condition on line 238 was never true

239 raise NotImplementedError(f"Transfer mode {transfer} not supported.") 

240 # ingest can occur from file->s3 and s3->s3 (source can be file or s3, 

241 # target will always be s3). File has to exist at target location. Two 

242 # Schemeless URIs are assumed to obey os.path rules. Equivalent to 

243 # os.path.exists(fullPath) check in PosixDatastore. 

244 srcUri = ButlerURI(path) 

245 if srcUri.scheme == 'file' or not srcUri.scheme: 245 ↛ 248line 245 didn't jump to line 248, because the condition on line 245 was never false

246 if not os.path.exists(srcUri.ospath): 246 ↛ 247line 246 didn't jump to line 247, because the condition on line 246 was never true

247 raise FileNotFoundError(f"File at '{srcUri}' does not exist.") 

248 elif srcUri.scheme == 's3': 

249 if not s3CheckFileExists(srcUri, client=self.client)[0]: 

250 raise FileNotFoundError(f"File at '{srcUri}' does not exist.") 

251 else: 

252 raise NotImplementedError(f"Scheme type {srcUri.scheme} not supported.") 

253 

254 if transfer is None: 254 ↛ 255line 254 didn't jump to line 255, because the condition on line 254 was never true

255 rootUri = ButlerURI(self.root) 

256 if srcUri.scheme == "file": 

257 raise RuntimeError(f"'{srcUri}' is not inside repository root '{rootUri}'. " 

258 "Ingesting local data to S3Datastore without upload " 

259 "to S3 is not allowed.") 

260 elif srcUri.scheme == "s3": 

261 if not srcUri.path.startswith(rootUri.path): 

262 raise RuntimeError(f"'{srcUri}' is not inside repository root '{rootUri}'.") 

263 return path 

264 

265 def _extractIngestInfo(self, path: str, ref: DatasetRef, *, 

266 formatter: Union[Formatter, Type[Formatter]], 

267 transfer: Optional[str] = None) -> StoredFileInfo: 

268 # Docstring inherited from FileLikeDatastore._extractIngestInfo. 

269 srcUri = ButlerURI(path) 

270 if transfer is None: 

271 rootUri = ButlerURI(self.root) 

272 p = pathlib.PurePosixPath(srcUri.relativeToPathRoot) 

273 pathInStore = str(p.relative_to(rootUri.relativeToPathRoot)) 

274 tgtLocation = self.locationFactory.fromPath(pathInStore) 

275 else: 

276 assert transfer == "move" or transfer == "copy", "Should be guaranteed by _standardizeIngestPath" 

277 if srcUri.scheme == "file": 277 ↛ 287line 277 didn't jump to line 287, because the condition on line 277 was never false

278 # source is on local disk. 

279 template = self.templates.getTemplate(ref) 

280 location = self.locationFactory.fromPath(template.format(ref)) 

281 tgtPathInStore = formatter.predictPathFromLocation(location) 

282 tgtLocation = self.locationFactory.fromPath(tgtPathInStore) 

283 self.client.upload_file(Bucket=tgtLocation.netloc, Key=tgtLocation.relativeToPathRoot, 

284 Filename=srcUri.ospath) 

285 if transfer == "move": 285 ↛ 286line 285 didn't jump to line 286, because the condition on line 285 was never true

286 os.remove(srcUri.ospath) 

287 elif srcUri.scheme == "s3": 

288 # source is another S3 Bucket 

289 relpath = srcUri.relativeToPathRoot 

290 copySrc = {"Bucket": srcUri.netloc, "Key": relpath} 

291 self.client.copy(copySrc, self.locationFactory.netloc, relpath) 

292 if transfer == "move": 

293 # https://github.com/boto/boto3/issues/507 - there is no 

294 # way of knowing if the file was actually deleted except 

295 # for checking all the keys again, reponse is HTTP 204 OK 

296 # response all the time 

297 self.client.delete(Bucket=srcUri.netloc, Key=relpath) 

298 p = pathlib.PurePosixPath(srcUri.relativeToPathRoot) 

299 relativeToDatastoreRoot = str(p.relative_to(rootUri.relativeToPathRoot)) 

300 tgtLocation = self.locationFactory.fromPath(relativeToDatastoreRoot) 

301 

302 # the file should exist on the bucket by now 

303 exists, size = s3CheckFileExists(path=tgtLocation.relativeToPathRoot, 

304 bucket=tgtLocation.netloc, 

305 client=self.client) 

306 

307 return StoredFileInfo(formatter=formatter, path=tgtLocation.pathInStore, 

308 storageClass=ref.datasetType.storageClass, 

309 component=ref.datasetType.component(), 

310 file_size=size, checksum=None)