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

21from __future__ import annotations 

22 

23"""Generic file-based datastore code.""" 

24 

25__all__ = ("FileLikeDatastore", ) 

26 

27import logging 

28from abc import abstractmethod 

29 

30from sqlalchemy import Integer, String 

31 

32from dataclasses import dataclass 

33from typing import ( 

34 TYPE_CHECKING, 

35 Any, 

36 ClassVar, 

37 Dict, 

38 Iterable, 

39 List, 

40 Mapping, 

41 Optional, 

42 Set, 

43 Tuple, 

44 Type, 

45 Union, 

46) 

47 

48from lsst.daf.butler import ( 

49 ButlerURI, 

50 CompositesMap, 

51 Config, 

52 FileDataset, 

53 DatasetRef, 

54 DatasetType, 

55 DatasetTypeNotSupportedError, 

56 Datastore, 

57 DatastoreConfig, 

58 DatastoreValidationError, 

59 FileDescriptor, 

60 FileTemplates, 

61 FileTemplateValidationError, 

62 Formatter, 

63 FormatterFactory, 

64 Location, 

65 LocationFactory, 

66 StorageClass, 

67 StoredFileInfo, 

68) 

69 

70from lsst.daf.butler import ddl 

71from lsst.daf.butler.registry.interfaces import ( 

72 ReadOnlyDatabaseError, 

73 DatastoreRegistryBridge, 

74 FakeDatasetRef, 

75) 

76 

77from lsst.daf.butler.core.repoRelocation import replaceRoot 

78from lsst.daf.butler.core.utils import getInstanceOf, getClassOf, transactional 

79from .genericDatastore import GenericBaseDatastore 

80 

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

82 from lsst.daf.butler import LookupKey 

83 from lsst.daf.butler.registry.interfaces import DatasetIdRef, DatastoreRegistryBridgeManager 

84 

85log = logging.getLogger(__name__) 

86 

87# String to use when a Python None is encountered 

88NULLSTR = "__NULL_STRING__" 

89 

90 

91class _IngestPrepData(Datastore.IngestPrepData): 

92 """Helper class for FileLikeDatastore ingest implementation. 

93 

94 Parameters 

95 ---------- 

96 datasets : `list` of `FileDataset` 

97 Files to be ingested by this datastore. 

98 """ 

99 def __init__(self, datasets: List[FileDataset]): 

100 super().__init__(ref for dataset in datasets for ref in dataset.refs) 

101 self.datasets = datasets 

102 

103 

104@dataclass(frozen=True) 

105class DatastoreFileGetInformation: 

106 """Collection of useful parameters needed to retrieve a file from 

107 a Datastore. 

108 """ 

109 

110 location: Location 

111 """The location from which to read the dataset.""" 

112 

113 formatter: Formatter 

114 """The `Formatter` to use to deserialize the dataset.""" 

115 

116 info: StoredFileInfo 

117 """Stored information about this file and its formatter.""" 

118 

119 assemblerParams: dict 

120 """Parameters to use for post-processing the retrieved dataset.""" 

121 

122 component: Optional[str] 

123 """The component to be retrieved (can be `None`).""" 

124 

125 readStorageClass: StorageClass 

126 """The `StorageClass` of the dataset being read.""" 

127 

128 

129class FileLikeDatastore(GenericBaseDatastore): 

130 """Generic Datastore for file-based implementations. 

131 

132 Should always be sub-classed since key abstract methods are missing. 

133 

134 Parameters 

135 ---------- 

136 config : `DatastoreConfig` or `str` 

137 Configuration as either a `Config` object or URI to file. 

138 bridgeManager : `DatastoreRegistryBridgeManager` 

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

140 butlerRoot : `str`, optional 

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

142 

143 Raises 

144 ------ 

145 ValueError 

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

147 configuration. 

148 """ 

149 

150 defaultConfigFile: ClassVar[Optional[str]] = None 

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

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

153 """ 

154 

155 root: str 

156 """Root directory or URI of this `Datastore`.""" 

157 

158 locationFactory: LocationFactory 

159 """Factory for creating locations relative to the datastore root.""" 

160 

161 formatterFactory: FormatterFactory 

162 """Factory for creating instances of formatters.""" 

163 

164 templates: FileTemplates 

165 """File templates that can be used by this `Datastore`.""" 

166 

167 composites: CompositesMap 

168 """Determines whether a dataset should be disassembled on put.""" 

169 

170 @classmethod 

171 def setConfigRoot(cls, root: str, config: Config, full: Config, overwrite: bool = True) -> None: 

172 """Set any filesystem-dependent config options for this Datastore to 

173 be appropriate for a new empty repository with the given root. 

174 

175 Parameters 

176 ---------- 

177 root : `str` 

178 URI to the root of the data repository. 

179 config : `Config` 

180 A `Config` to update. Only the subset understood by 

181 this component will be updated. Will not expand 

182 defaults. 

183 full : `Config` 

184 A complete config with all defaults expanded that can be 

185 converted to a `DatastoreConfig`. Read-only and will not be 

186 modified by this method. 

187 Repository-specific options that should not be obtained 

188 from defaults when Butler instances are constructed 

189 should be copied from ``full`` to ``config``. 

190 overwrite : `bool`, optional 

191 If `False`, do not modify a value in ``config`` if the value 

192 already exists. Default is always to overwrite with the provided 

193 ``root``. 

194 

195 Notes 

196 ----- 

197 If a keyword is explicitly defined in the supplied ``config`` it 

198 will not be overridden by this method if ``overwrite`` is `False`. 

199 This allows explicit values set in external configs to be retained. 

200 """ 

201 Config.updateParameters(DatastoreConfig, config, full, 

202 toUpdate={"root": root}, 

203 toCopy=("cls", ("records", "table")), overwrite=overwrite) 

204 

205 @classmethod 

206 def makeTableSpec(cls) -> ddl.TableSpec: 

207 return ddl.TableSpec( 

208 fields=[ 

209 ddl.FieldSpec(name="dataset_id", dtype=Integer, primaryKey=True), 

210 ddl.FieldSpec(name="path", dtype=String, length=256, nullable=False), 

211 ddl.FieldSpec(name="formatter", dtype=String, length=128, nullable=False), 

212 ddl.FieldSpec(name="storage_class", dtype=String, length=64, nullable=False), 

213 # Use empty string to indicate no component 

214 ddl.FieldSpec(name="component", dtype=String, length=32, primaryKey=True), 

215 # TODO: should checksum be Base64Bytes instead? 

216 ddl.FieldSpec(name="checksum", dtype=String, length=128, nullable=True), 

217 ddl.FieldSpec(name="file_size", dtype=Integer, nullable=True), 

218 ], 

219 unique=frozenset(), 

220 ) 

221 

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

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

224 super().__init__(config, bridgeManager) 

225 if "root" not in self.config: 225 ↛ 226line 225 didn't jump to line 226, because the condition on line 225 was never true

226 raise ValueError("No root directory specified in configuration") 

227 

228 # Name ourselves either using an explicit name or a name 

229 # derived from the (unexpanded) root 

230 if "name" in self.config: 

231 self.name = self.config["name"] 

232 else: 

233 # We use the unexpanded root in the name to indicate that this 

234 # datastore can be moved without having to update registry. 

235 self.name = "{}@{}".format(type(self).__name__, 

236 self.config["root"]) 

237 

238 # Support repository relocation in config 

239 # Existence of self.root is checked in subclass 

240 self.root = replaceRoot(self.config["root"], butlerRoot) 

241 

242 self.locationFactory = LocationFactory(self.root) 

243 self.formatterFactory = FormatterFactory() 

244 

245 # Now associate formatters with storage classes 

246 self.formatterFactory.registerFormatters(self.config["formatters"], 

247 universe=bridgeManager.universe) 

248 

249 # Read the file naming templates 

250 self.templates = FileTemplates(self.config["templates"], 

251 universe=bridgeManager.universe) 

252 

253 # See if composites should be disassembled 

254 self.composites = CompositesMap(self.config["composites"], 

255 universe=bridgeManager.universe) 

256 

257 tableName = self.config["records", "table"] 

258 try: 

259 # Storage of paths and formatters, keyed by dataset_id 

260 self._table = bridgeManager.opaque.register(tableName, self.makeTableSpec()) 

261 # Interface to Registry. 

262 self._bridge = bridgeManager.register(self.name) 

263 except ReadOnlyDatabaseError: 

264 # If the database is read only and we just tried and failed to 

265 # create a table, it means someone is trying to create a read-only 

266 # butler client for an empty repo. That should be okay, as long 

267 # as they then try to get any datasets before some other client 

268 # creates the table. Chances are they'rejust validating 

269 # configuration. 

270 pass 

271 

272 # Determine whether checksums should be used 

273 self.useChecksum = self.config.get("checksum", True) 

274 

275 def __str__(self) -> str: 

276 return self.root 

277 

278 @property 

279 def bridge(self) -> DatastoreRegistryBridge: 

280 return self._bridge 

281 

282 @abstractmethod 

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

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

285 location. 

286 

287 Parameters 

288 ---------- 

289 location : `Location` 

290 Expected location of the artifact associated with this datastore. 

291 

292 Returns 

293 ------- 

294 exists : `bool` 

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

296 """ 

297 raise NotImplementedError() 

298 

299 @abstractmethod 

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

301 """Delete the artifact from the datastore. 

302 

303 Parameters 

304 ---------- 

305 location : `Location` 

306 Location of the artifact associated with this datastore. 

307 """ 

308 raise NotImplementedError() 

309 

310 def addStoredItemInfo(self, refs: Iterable[DatasetRef], infos: Iterable[StoredFileInfo]) -> None: 

311 # Docstring inherited from GenericBaseDatastore 

312 records = [] 

313 for ref, info in zip(refs, infos): 

314 # Component should come from ref and fall back on info 

315 component = ref.datasetType.component() 

316 if component is None and info.component is not None: 316 ↛ 317line 316 didn't jump to line 317, because the condition on line 316 was never true

317 component = info.component 

318 if component is None: 

319 # Use empty string since we want this to be part of the 

320 # primary key. 

321 component = NULLSTR 

322 records.append( 

323 dict(dataset_id=ref.id, formatter=info.formatter, path=info.path, 

324 storage_class=info.storageClass.name, component=component, 

325 checksum=info.checksum, file_size=info.file_size) 

326 ) 

327 self._table.insert(*records) 

328 

329 def getStoredItemInfo(self, ref: DatasetIdRef) -> StoredFileInfo: 

330 # Docstring inherited from GenericBaseDatastore 

331 

332 if ref.id is None: 332 ↛ 333line 332 didn't jump to line 333, because the condition on line 332 was never true

333 raise RuntimeError("Unable to retrieve information for unresolved DatasetRef") 

334 

335 where: Dict[str, Union[int, str]] = {"dataset_id": ref.id} 

336 

337 # If we have no component we want the row from this table without 

338 # a component. If we do have a component we either need the row 

339 # with no component or the row with the component, depending on how 

340 # this dataset was dissassembled. 

341 

342 # if we are emptying trash we won't have real refs so can't constrain 

343 # by component. Will need to fix this to return multiple matches 

344 # in future. 

345 component = None 

346 try: 

347 component = ref.datasetType.component() 

348 except AttributeError: 

349 pass 

350 else: 

351 if component is None: 351 ↛ 356line 351 didn't jump to line 356, because the condition on line 351 was never false

352 where["component"] = NULLSTR 

353 

354 # Look for the dataset_id -- there might be multiple matches 

355 # if we have disassembled the dataset. 

356 records = list(self._table.fetch(**where)) 

357 if len(records) == 0: 357 ↛ 358line 357 didn't jump to line 358, because the condition on line 357 was never true

358 raise KeyError(f"Unable to retrieve location associated with dataset {ref}.") 

359 

360 # if we are not asking for a component 

361 if not component and len(records) != 1: 361 ↛ 362line 361 didn't jump to line 362, because the condition on line 361 was never true

362 raise RuntimeError(f"Got {len(records)} from location query of dataset {ref}") 

363 

364 # if we had a FakeDatasetRef we pick the first record regardless 

365 if isinstance(ref, FakeDatasetRef): 365 ↛ 366line 365 didn't jump to line 366, because the condition on line 365 was never true

366 record = records[0] 

367 else: 

368 records_by_component = {} 

369 for r in records: 

370 this_component = r["component"] if r["component"] and r["component"] != NULLSTR else None 

371 records_by_component[this_component] = r 

372 

373 # Look for component by name else fall back to the parent 

374 for lookup in (component, None): 374 ↛ 379line 374 didn't jump to line 379, because the loop on line 374 didn't complete

375 if lookup in records_by_component: 375 ↛ 374line 375 didn't jump to line 374, because the condition on line 375 was never false

376 record = records_by_component[lookup] 

377 break 

378 else: 

379 raise KeyError(f"Unable to retrieve location for component {component} associated with " 

380 f"dataset {ref}.") 

381 

382 # Convert name of StorageClass to instance 

383 storageClass = self.storageClassFactory.getStorageClass(record["storage_class"]) 

384 

385 return StoredFileInfo(formatter=record["formatter"], 

386 path=record["path"], 

387 storageClass=storageClass, 

388 component=component, 

389 checksum=record["checksum"], 

390 file_size=record["file_size"]) 

391 

392 def getStoredItemsInfo(self, ref: DatasetIdRef) -> List[StoredFileInfo]: 

393 # Docstring inherited from GenericBaseDatastore 

394 

395 # Look for the dataset_id -- there might be multiple matches 

396 # if we have disassembled the dataset. 

397 records = list(self._table.fetch(dataset_id=ref.id)) 

398 

399 results = [] 

400 for record in records: 

401 # Convert name of StorageClass to instance 

402 storageClass = self.storageClassFactory.getStorageClass(record["storage_class"]) 

403 component = record["component"] if (record["component"] 

404 and record["component"] != NULLSTR) else None 

405 

406 info = StoredFileInfo(formatter=record["formatter"], 

407 path=record["path"], 

408 storageClass=storageClass, 

409 component=component, 

410 checksum=record["checksum"], 

411 file_size=record["file_size"]) 

412 results.append(info) 

413 

414 return results 

415 

416 def _registered_refs_per_artifact(self, pathInStore: str) -> Set[int]: 

417 """Return all dataset refs associated with the supplied path. 

418 

419 Parameters 

420 ---------- 

421 pathInStore : `str` 

422 Path of interest in the data store. 

423 

424 Returns 

425 ------- 

426 ids : `set` of `int` 

427 All `DatasetRef` IDs associated with this path. 

428 """ 

429 records = list(self._table.fetch(path=pathInStore)) 

430 ids = {r["dataset_id"] for r in records} 

431 return ids 

432 

433 def removeStoredItemInfo(self, ref: DatasetIdRef) -> None: 

434 # Docstring inherited from GenericBaseDatastore 

435 self._table.delete(dataset_id=ref.id) 

436 

437 def _get_dataset_location_info(self, 

438 ref: DatasetRef) -> Tuple[Optional[Location], Optional[StoredFileInfo]]: 

439 """Find the `Location` of the requested dataset in the 

440 `Datastore` and the associated stored file information. 

441 

442 Parameters 

443 ---------- 

444 ref : `DatasetRef` 

445 Reference to the required `Dataset`. 

446 

447 Returns 

448 ------- 

449 location : `Location` 

450 Location of the dataset within the datastore. 

451 Returns `None` if the dataset can not be located. 

452 info : `StoredFileInfo` 

453 Stored information about this file and its formatter. 

454 """ 

455 # Get the file information (this will fail if no file) 

456 try: 

457 storedFileInfo = self.getStoredItemInfo(ref) 

458 except KeyError: 

459 return None, None 

460 

461 # Use the path to determine the location 

462 location = self.locationFactory.fromPath(storedFileInfo.path) 

463 

464 return location, storedFileInfo 

465 

466 def _get_dataset_locations_info(self, ref: DatasetIdRef) -> List[Tuple[Location, StoredFileInfo]]: 

467 r"""Find all the `Location`\ s of the requested dataset in the 

468 `Datastore` and the associated stored file information. 

469 

470 Parameters 

471 ---------- 

472 ref : `DatasetRef` 

473 Reference to the required `Dataset`. 

474 

475 Returns 

476 ------- 

477 results : `list` [`tuple` [`Location`, `StoredFileInfo` ]] 

478 Location of the dataset within the datastore and 

479 stored information about each file and its formatter. 

480 """ 

481 # Get the file information (this will fail if no file) 

482 records = self.getStoredItemsInfo(ref) 

483 

484 # Use the path to determine the location 

485 return [(self.locationFactory.fromPath(r.path), r) for r in records] 

486 

487 def _can_remove_dataset_artifact(self, ref: DatasetIdRef, location: Location) -> bool: 

488 """Check that there is only one dataset associated with the 

489 specified artifact. 

490 

491 Parameters 

492 ---------- 

493 ref : `DatasetRef` or `FakeDatasetRef` 

494 Dataset to be removed. 

495 location : `Location` 

496 The location of the artifact to be removed. 

497 

498 Returns 

499 ------- 

500 can_remove : `Bool` 

501 True if the artifact can be safely removed. 

502 """ 

503 

504 # Get all entries associated with this path 

505 allRefs = self._registered_refs_per_artifact(location.pathInStore) 

506 if not allRefs: 506 ↛ 507line 506 didn't jump to line 507, because the condition on line 506 was never true

507 raise RuntimeError(f"Datastore inconsistency error. {location.pathInStore} not in registry") 

508 

509 # Get all the refs associated with this dataset if it is a composite 

510 theseRefs = {r.id for r in ref.allRefs()} 

511 

512 # Remove these refs from all the refs and if there is nothing left 

513 # then we can delete 

514 remainingRefs = allRefs - theseRefs 

515 

516 if remainingRefs: 

517 return False 

518 return True 

519 

520 def _prepare_for_get(self, ref: DatasetRef, 

521 parameters: Optional[Mapping[str, Any]] = None) -> List[DatastoreFileGetInformation]: 

522 """Check parameters for ``get`` and obtain formatter and 

523 location. 

524 

525 Parameters 

526 ---------- 

527 ref : `DatasetRef` 

528 Reference to the required Dataset. 

529 parameters : `dict` 

530 `StorageClass`-specific parameters that specify, for example, 

531 a slice of the dataset to be loaded. 

532 

533 Returns 

534 ------- 

535 getInfo : `list` [`DatastoreFileGetInformation`] 

536 Parameters needed to retrieve each file. 

537 """ 

538 log.debug("Retrieve %s from %s with parameters %s", ref, self.name, parameters) 

539 

540 # Get file metadata and internal metadata 

541 fileLocations = self._get_dataset_locations_info(ref) 

542 if not fileLocations: 

543 raise FileNotFoundError(f"Could not retrieve dataset {ref}.") 

544 

545 # The storage class we want to use eventually 

546 refStorageClass = ref.datasetType.storageClass 

547 

548 # Check that the supplied parameters are suitable for the type read 

549 refStorageClass.validateParameters(parameters) 

550 

551 if len(fileLocations) > 1: 

552 disassembled = True 

553 else: 

554 disassembled = False 

555 

556 # Is this a component request? 

557 refComponent = ref.datasetType.component() 

558 

559 fileGetInfo = [] 

560 for location, storedFileInfo in fileLocations: 

561 

562 # The storage class used to write the file 

563 writeStorageClass = storedFileInfo.storageClass 

564 

565 # If this has been disassembled we need read to match the write 

566 if disassembled: 

567 readStorageClass = writeStorageClass 

568 else: 

569 readStorageClass = refStorageClass 

570 

571 formatter = getInstanceOf(storedFileInfo.formatter, 

572 FileDescriptor(location, readStorageClass=readStorageClass, 

573 storageClass=writeStorageClass, parameters=parameters), 

574 ref.dataId) 

575 

576 _, notFormatterParams = formatter.segregateParameters() 

577 

578 # Of the remaining parameters, extract the ones supported by 

579 # this StorageClass (for components not all will be handled) 

580 assemblerParams = readStorageClass.filterParameters(notFormatterParams) 

581 

582 # The ref itself could be a component if the dataset was 

583 # disassembled by butler, or we disassembled in datastore and 

584 # components came from the datastore records 

585 component = storedFileInfo.component if storedFileInfo.component else refComponent 

586 

587 fileGetInfo.append(DatastoreFileGetInformation(location, formatter, storedFileInfo, 

588 assemblerParams, component, readStorageClass)) 

589 

590 return fileGetInfo 

591 

592 def _prepare_for_put(self, inMemoryDataset: Any, ref: DatasetRef) -> Tuple[Location, Formatter]: 

593 """Check the arguments for ``put`` and obtain formatter and 

594 location. 

595 

596 Parameters 

597 ---------- 

598 inMemoryDataset : `object` 

599 The dataset to store. 

600 ref : `DatasetRef` 

601 Reference to the associated Dataset. 

602 

603 Returns 

604 ------- 

605 location : `Location` 

606 The location to write the dataset. 

607 formatter : `Formatter` 

608 The `Formatter` to use to write the dataset. 

609 

610 Raises 

611 ------ 

612 TypeError 

613 Supplied object and storage class are inconsistent. 

614 DatasetTypeNotSupportedError 

615 The associated `DatasetType` is not handled by this datastore. 

616 """ 

617 self._validate_put_parameters(inMemoryDataset, ref) 

618 

619 # Work out output file name 

620 try: 

621 template = self.templates.getTemplate(ref) 

622 except KeyError as e: 

623 raise DatasetTypeNotSupportedError(f"Unable to find template for {ref}") from e 

624 

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

626 

627 # Get the formatter based on the storage class 

628 storageClass = ref.datasetType.storageClass 

629 try: 

630 formatter = self.formatterFactory.getFormatter(ref, 

631 FileDescriptor(location, 

632 storageClass=storageClass), 

633 ref.dataId) 

634 except KeyError as e: 

635 raise DatasetTypeNotSupportedError(f"Unable to find formatter for {ref}") from e 

636 

637 return location, formatter 

638 

639 @abstractmethod 

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

641 """Standardize the path of a to-be-ingested file. 

642 

643 Parameters 

644 ---------- 

645 path : `str` 

646 Path of a file to be ingested. 

647 transfer : `str`, optional 

648 How (and whether) the dataset should be added to the datastore. 

649 See `ingest` for details of transfer modes. 

650 This implementation is provided only so 

651 `NotImplementedError` can be raised if the mode is not supported; 

652 actual transfers are deferred to `_extractIngestInfo`. 

653 

654 Returns 

655 ------- 

656 path : `str` 

657 New path in what the datastore considers standard form. 

658 

659 Notes 

660 ----- 

661 Subclasses of `FileLikeDatastore` should implement this method instead 

662 of `_prepIngest`. It should not modify the data repository or given 

663 file in any way. 

664 

665 Raises 

666 ------ 

667 NotImplementedError 

668 Raised if the datastore does not support the given transfer mode 

669 (including the case where ingest is not supported at all). 

670 FileNotFoundError 

671 Raised if one of the given files does not exist. 

672 """ 

673 raise NotImplementedError("Must be implemented by subclasses.") 

674 

675 @abstractmethod 

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

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

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

679 """Relocate (if necessary) and extract `StoredFileInfo` from a 

680 to-be-ingested file. 

681 

682 Parameters 

683 ---------- 

684 path : `str` 

685 Path of a file to be ingested. 

686 ref : `DatasetRef` 

687 Reference for the dataset being ingested. Guaranteed to have 

688 ``dataset_id not None`. 

689 formatter : `type` or `Formatter` 

690 `Formatter` subclass to use for this dataset or an instance. 

691 transfer : `str`, optional 

692 How (and whether) the dataset should be added to the datastore. 

693 See `ingest` for details of transfer modes. 

694 

695 Returns 

696 ------- 

697 info : `StoredFileInfo` 

698 Internal datastore record for this file. This will be inserted by 

699 the caller; the `_extractIngestInfo` is only resposible for 

700 creating and populating the struct. 

701 

702 Raises 

703 ------ 

704 FileNotFoundError 

705 Raised if one of the given files does not exist. 

706 FileExistsError 

707 Raised if transfer is not `None` but the (internal) location the 

708 file would be moved to is already occupied. 

709 """ 

710 raise NotImplementedError("Must be implemented by subclasses.") 

711 

712 def _prepIngest(self, *datasets: FileDataset, transfer: Optional[str] = None) -> _IngestPrepData: 

713 # Docstring inherited from Datastore._prepIngest. 

714 filtered = [] 

715 for dataset in datasets: 

716 acceptable = [ref for ref in dataset.refs if self.constraints.isAcceptable(ref)] 

717 if not acceptable: 

718 continue 

719 else: 

720 dataset.refs = acceptable 

721 if dataset.formatter is None: 

722 dataset.formatter = self.formatterFactory.getFormatterClass(dataset.refs[0]) 

723 else: 

724 assert isinstance(dataset.formatter, (type, str)) 

725 dataset.formatter = getClassOf(dataset.formatter) 

726 dataset.path = self._standardizeIngestPath(dataset.path, transfer=transfer) 

727 filtered.append(dataset) 

728 return _IngestPrepData(filtered) 

729 

730 @transactional 

731 def _finishIngest(self, prepData: Datastore.IngestPrepData, *, transfer: Optional[str] = None) -> None: 

732 # Docstring inherited from Datastore._finishIngest. 

733 refsAndInfos = [] 

734 for dataset in prepData.datasets: 

735 # Do ingest as if the first dataset ref is associated with the file 

736 info = self._extractIngestInfo(dataset.path, dataset.refs[0], formatter=dataset.formatter, 

737 transfer=transfer) 

738 refsAndInfos.extend([(ref, info) for ref in dataset.refs]) 

739 self._register_datasets(refsAndInfos) 

740 

741 @abstractmethod 

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

743 """Write out in memory dataset to datastore. 

744 

745 Parameters 

746 ---------- 

747 inMemoryDataset : `object` 

748 Dataset to write to datastore. 

749 ref : `DatasetRef` 

750 Registry information associated with this dataset. 

751 

752 Returns 

753 ------- 

754 info : `StoredFileInfo` 

755 Information describin the artifact written to the datastore. 

756 """ 

757 raise NotImplementedError() 

758 

759 @abstractmethod 

760 def _read_artifact_into_memory(self, getInfo: DatastoreFileGetInformation, 

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

762 """Read the artifact from datastore into in memory object. 

763 

764 Parameters 

765 ---------- 

766 getInfo : `DatastoreFileGetInformation` 

767 Information about the artifact within the datastore. 

768 ref : `DatasetRef` 

769 The registry information associated with this artifact. 

770 isComponent : `bool` 

771 Flag to indicate if a component is being read from this artifact. 

772 

773 Returns 

774 ------- 

775 inMemoryDataset : `object` 

776 The artifact as a python object. 

777 """ 

778 raise NotImplementedError() 

779 

780 def exists(self, ref: DatasetRef) -> bool: 

781 """Check if the dataset exists in the datastore. 

782 

783 Parameters 

784 ---------- 

785 ref : `DatasetRef` 

786 Reference to the required dataset. 

787 

788 Returns 

789 ------- 

790 exists : `bool` 

791 `True` if the entity exists in the `Datastore`. 

792 """ 

793 fileLocations = self._get_dataset_locations_info(ref) 

794 if not fileLocations: 

795 return False 

796 for location, _ in fileLocations: 

797 if not self._artifact_exists(location): 

798 return False 

799 

800 return True 

801 

802 def getURIs(self, ref: DatasetRef, 

803 predict: bool = False) -> Tuple[Optional[ButlerURI], Dict[str, ButlerURI]]: 

804 """Return URIs associated with dataset. 

805 

806 Parameters 

807 ---------- 

808 ref : `DatasetRef` 

809 Reference to the required dataset. 

810 predict : `bool`, optional 

811 If the datastore does not know about the dataset, should it 

812 return a predicted URI or not? 

813 

814 Returns 

815 ------- 

816 primary : `ButlerURI` 

817 The URI to the primary artifact associated with this dataset. 

818 If the dataset was disassembled within the datastore this 

819 may be `None`. 

820 components : `dict` 

821 URIs to any components associated with the dataset artifact. 

822 Can be empty if there are no components. 

823 """ 

824 

825 primary: Optional[ButlerURI] = None 

826 components: Dict[str, ButlerURI] = {} 

827 

828 # if this has never been written then we have to guess 

829 if not self.exists(ref): 

830 if not predict: 

831 raise FileNotFoundError("Dataset {} not in this datastore".format(ref)) 

832 

833 def predictLocation(thisRef: DatasetRef) -> Location: 

834 template = self.templates.getTemplate(thisRef) 

835 location = self.locationFactory.fromPath(template.format(thisRef)) 

836 storageClass = ref.datasetType.storageClass 

837 formatter = self.formatterFactory.getFormatter(thisRef, 

838 FileDescriptor(location, 

839 storageClass=storageClass)) 

840 # Try to use the extension attribute but ignore problems if the 

841 # formatter does not define one. 

842 try: 

843 location = formatter.makeUpdatedLocation(location) 

844 except Exception: 

845 # Use the default extension 

846 pass 

847 return location 

848 

849 doDisassembly = self.composites.shouldBeDisassembled(ref) 

850 

851 if doDisassembly: 

852 

853 for component, componentStorage in ref.datasetType.storageClass.components.items(): 

854 compTypeName = ref.datasetType.componentTypeName(component) 

855 compType = DatasetType(compTypeName, dimensions=ref.datasetType.dimensions, 

856 storageClass=componentStorage) 

857 compRef = DatasetRef(compType, ref.dataId, id=ref.id, run=ref.run, conform=False) 

858 

859 compLocation = predictLocation(compRef) 

860 

861 # Add a URI fragment to indicate this is a guess 

862 components[component] = ButlerURI(compLocation.uri + "#predicted") 

863 

864 else: 

865 

866 location = predictLocation(ref) 

867 

868 # Add a URI fragment to indicate this is a guess 

869 primary = ButlerURI(location.uri + "#predicted") 

870 

871 return primary, components 

872 

873 # If this is a ref that we have written we can get the path. 

874 # Get file metadata and internal metadata 

875 fileLocations = self._get_dataset_locations_info(ref) 

876 

877 if not fileLocations: 877 ↛ 878line 877 didn't jump to line 878, because the condition on line 877 was never true

878 raise RuntimeError(f"Unexpectedly got no artifacts for dataset {ref}") 

879 

880 if len(fileLocations) == 1: 

881 # No disassembly so this is the primary URI 

882 primary = ButlerURI(fileLocations[0][0].uri) 

883 

884 else: 

885 for location, storedFileInfo in fileLocations: 

886 if storedFileInfo.component is None: 886 ↛ 887line 886 didn't jump to line 887, because the condition on line 886 was never true

887 raise RuntimeError(f"Unexpectedly got no component name for a component at {location}") 

888 components[storedFileInfo.component] = ButlerURI(location.uri) 

889 

890 return primary, components 

891 

892 def getURI(self, ref: DatasetRef, predict: bool = False) -> ButlerURI: 

893 """URI to the Dataset. 

894 

895 Parameters 

896 ---------- 

897 ref : `DatasetRef` 

898 Reference to the required Dataset. 

899 predict : `bool` 

900 If `True`, allow URIs to be returned of datasets that have not 

901 been written. 

902 

903 Returns 

904 ------- 

905 uri : `str` 

906 URI pointing to the dataset within the datastore. If the 

907 dataset does not exist in the datastore, and if ``predict`` is 

908 `True`, the URI will be a prediction and will include a URI 

909 fragment "#predicted". 

910 If the datastore does not have entities that relate well 

911 to the concept of a URI the returned URI will be 

912 descriptive. The returned URI is not guaranteed to be obtainable. 

913 

914 Raises 

915 ------ 

916 FileNotFoundError 

917 Raised if a URI has been requested for a dataset that does not 

918 exist and guessing is not allowed. 

919 RuntimeError 

920 Raised if a request is made for a single URI but multiple URIs 

921 are associated with this dataset. 

922 

923 Notes 

924 ----- 

925 When a predicted URI is requested an attempt will be made to form 

926 a reasonable URI based on file templates and the expected formatter. 

927 """ 

928 primary, components = self.getURIs(ref, predict) 

929 if primary is None or components: 929 ↛ 930line 929 didn't jump to line 930, because the condition on line 929 was never true

930 raise RuntimeError(f"Dataset ({ref}) includes distinct URIs for components. " 

931 "Use Dataastore.getURIs() instead.") 

932 return primary 

933 

934 def get(self, ref: DatasetRef, parameters: Optional[Mapping[str, Any]] = None) -> Any: 

935 """Load an InMemoryDataset from the store. 

936 

937 Parameters 

938 ---------- 

939 ref : `DatasetRef` 

940 Reference to the required Dataset. 

941 parameters : `dict` 

942 `StorageClass`-specific parameters that specify, for example, 

943 a slice of the dataset to be loaded. 

944 

945 Returns 

946 ------- 

947 inMemoryDataset : `object` 

948 Requested dataset or slice thereof as an InMemoryDataset. 

949 

950 Raises 

951 ------ 

952 FileNotFoundError 

953 Requested dataset can not be retrieved. 

954 TypeError 

955 Return value from formatter has unexpected type. 

956 ValueError 

957 Formatter failed to process the dataset. 

958 """ 

959 allGetInfo = self._prepare_for_get(ref, parameters) 

960 refComponent = ref.datasetType.component() 

961 

962 if len(allGetInfo) > 1 and not refComponent: 

963 # This was a disassembled dataset spread over multiple files 

964 # and we need to put them all back together again. 

965 # Read into memory and then assemble 

966 usedParams = set() 

967 components = {} 

968 for getInfo in allGetInfo: 

969 # assemblerParams are parameters not understood by the 

970 # associated formatter. 

971 usedParams.update(set(getInfo.assemblerParams)) 

972 

973 component = getInfo.component 

974 # We do not want the formatter to think it's reading 

975 # a component though because it is really reading a 

976 # standalone dataset -- always tell reader it is not a 

977 # component. 

978 components[component] = self._read_artifact_into_memory(getInfo, ref, isComponent=False) 

979 

980 inMemoryDataset = ref.datasetType.storageClass.assembler().assemble(components) 

981 

982 # Any unused parameters will have to be passed to the assembler 

983 if parameters: 

984 unusedParams = {k: v for k, v in parameters.items() if k not in usedParams} 

985 else: 

986 unusedParams = {} 

987 

988 # Process parameters 

989 return ref.datasetType.storageClass.assembler().handleParameters(inMemoryDataset, 

990 parameters=unusedParams) 

991 

992 else: 

993 # Single file request or component from that composite file 

994 allComponents = {i.component: i for i in allGetInfo} 

995 for lookup in (refComponent, None): 995 ↛ 1000line 995 didn't jump to line 1000, because the loop on line 995 didn't complete

996 if lookup in allComponents: 996 ↛ 995line 996 didn't jump to line 995, because the condition on line 996 was never false

997 getInfo = allComponents[lookup] 

998 break 

999 else: 

1000 raise FileNotFoundError(f"Component {refComponent} not found " 

1001 f"for ref {ref} in datastore {self.name}") 

1002 

1003 return self._read_artifact_into_memory(getInfo, ref, isComponent=getInfo.component is not None) 

1004 

1005 @transactional 

1006 def put(self, inMemoryDataset: Any, ref: DatasetRef) -> None: 

1007 """Write a InMemoryDataset with a given `DatasetRef` to the store. 

1008 

1009 Parameters 

1010 ---------- 

1011 inMemoryDataset : `object` 

1012 The dataset to store. 

1013 ref : `DatasetRef` 

1014 Reference to the associated Dataset. 

1015 

1016 Raises 

1017 ------ 

1018 TypeError 

1019 Supplied object and storage class are inconsistent. 

1020 DatasetTypeNotSupportedError 

1021 The associated `DatasetType` is not handled by this datastore. 

1022 

1023 Notes 

1024 ----- 

1025 If the datastore is configured to reject certain dataset types it 

1026 is possible that the put will fail and raise a 

1027 `DatasetTypeNotSupportedError`. The main use case for this is to 

1028 allow `ChainedDatastore` to put to multiple datastores without 

1029 requiring that every datastore accepts the dataset. 

1030 """ 

1031 

1032 doDisassembly = self.composites.shouldBeDisassembled(ref) 

1033 # doDisassembly = True 

1034 

1035 artifacts = [] 

1036 if doDisassembly: 

1037 components = ref.datasetType.storageClass.assembler().disassemble(inMemoryDataset) 

1038 for component, componentInfo in components.items(): 

1039 compTypeName = ref.datasetType.componentTypeName(component) 

1040 # Don't recurse because we want to take advantage of 

1041 # bulk insert -- need a new DatasetRef that refers to the 

1042 # same dataset_id but has the component DatasetType 

1043 # DatasetType does not refer to the types of components 

1044 # So we construct one ourselves. 

1045 compType = DatasetType(compTypeName, dimensions=ref.datasetType.dimensions, 

1046 storageClass=componentInfo.storageClass) 

1047 compRef = DatasetRef(compType, ref.dataId, id=ref.id, run=ref.run, conform=False) 

1048 storedInfo = self._write_in_memory_to_artifact(componentInfo.component, compRef) 

1049 artifacts.append((compRef, storedInfo)) 

1050 else: 

1051 # Write the entire thing out 

1052 storedInfo = self._write_in_memory_to_artifact(inMemoryDataset, ref) 

1053 artifacts.append((ref, storedInfo)) 

1054 

1055 self._register_datasets(artifacts) 

1056 

1057 @transactional 

1058 def trash(self, ref: DatasetRef, ignore_errors: bool = True) -> None: 

1059 """Indicate to the datastore that a dataset can be removed. 

1060 

1061 Parameters 

1062 ---------- 

1063 ref : `DatasetRef` 

1064 Reference to the required Dataset. 

1065 ignore_errors : `bool` 

1066 If `True` return without error even if something went wrong. 

1067 Problems could occur if another process is simultaneously trying 

1068 to delete. 

1069 

1070 Raises 

1071 ------ 

1072 FileNotFoundError 

1073 Attempt to remove a dataset that does not exist. 

1074 """ 

1075 # Get file metadata and internal metadata 

1076 log.debug("Trashing %s in datastore %s", ref, self.name) 

1077 

1078 fileLocations = self._get_dataset_locations_info(ref) 

1079 

1080 if not fileLocations: 

1081 err_msg = f"Requested dataset to trash ({ref}) is not known to datastore {self.name}" 

1082 if ignore_errors: 

1083 log.warning(err_msg) 

1084 return 

1085 else: 

1086 raise FileNotFoundError(err_msg) 

1087 

1088 for location, storedFileInfo in fileLocations: 

1089 if not self._artifact_exists(location): 1089 ↛ 1090line 1089 didn't jump to line 1090, because the condition on line 1089 was never true

1090 err_msg = f"Dataset is known to datastore {self.name} but " \ 

1091 f"associated artifact ({location.uri}) is missing" 

1092 if ignore_errors: 

1093 log.warning(err_msg) 

1094 return 

1095 else: 

1096 raise FileNotFoundError(err_msg) 

1097 

1098 # Mark dataset as trashed 

1099 try: 

1100 self._move_to_trash_in_registry(ref) 

1101 except Exception as e: 

1102 if ignore_errors: 

1103 log.warning(f"Attempted to mark dataset ({ref}) to be trashed in datastore {self.name} " 

1104 f"but encountered an error: {e}") 

1105 pass 

1106 else: 

1107 raise 

1108 

1109 @transactional 

1110 def emptyTrash(self, ignore_errors: bool = True) -> None: 

1111 """Remove all datasets from the trash. 

1112 

1113 Parameters 

1114 ---------- 

1115 ignore_errors : `bool` 

1116 If `True` return without error even if something went wrong. 

1117 Problems could occur if another process is simultaneously trying 

1118 to delete. 

1119 """ 

1120 log.debug("Emptying trash in datastore %s", self.name) 

1121 # Context manager will empty trash iff we finish it without raising. 

1122 with self._bridge.emptyTrash() as trashed: 

1123 for ref in trashed: 

1124 fileLocations = self._get_dataset_locations_info(ref) 

1125 

1126 if not fileLocations: 1126 ↛ 1127line 1126 didn't jump to line 1127, because the condition on line 1126 was never true

1127 err_msg = f"Requested dataset ({ref}) does not exist in datastore {self.name}" 

1128 if ignore_errors: 

1129 log.warning(err_msg) 

1130 continue 

1131 else: 

1132 raise FileNotFoundError(err_msg) 

1133 

1134 for location, _ in fileLocations: 

1135 

1136 if not self._artifact_exists(location): 1136 ↛ 1137line 1136 didn't jump to line 1137, because the condition on line 1136 was never true

1137 err_msg = f"Dataset {location.uri} no longer present in datastore {self.name}" 

1138 if ignore_errors: 

1139 log.warning(err_msg) 

1140 continue 

1141 else: 

1142 raise FileNotFoundError(err_msg) 

1143 

1144 # Can only delete the artifact if there are no references 

1145 # to the file from untrashed dataset refs. 

1146 if self._can_remove_dataset_artifact(ref, location): 

1147 # Point of no return for this artifact 

1148 log.debug("Removing artifact %s from datastore %s", location.uri, self.name) 

1149 try: 

1150 self._delete_artifact(location) 

1151 except Exception as e: 

1152 if ignore_errors: 

1153 log.critical("Encountered error removing artifact %s from datastore %s: %s", 

1154 location.uri, self.name, e) 

1155 else: 

1156 raise 

1157 

1158 # Now must remove the entry from the internal registry even if 

1159 # the artifact removal failed and was ignored, 

1160 # otherwise the removal check above will never be true 

1161 try: 

1162 # There may be multiple rows associated with this ref 

1163 # depending on disassembly 

1164 self.removeStoredItemInfo(ref) 

1165 except Exception as e: 

1166 if ignore_errors: 

1167 log.warning("Error removing dataset %s (%s) from internal registry of %s: %s", 

1168 ref.id, location.uri, self.name, e) 

1169 continue 

1170 else: 

1171 raise FileNotFoundError(err_msg) 

1172 

1173 def validateConfiguration(self, entities: Iterable[Union[DatasetRef, DatasetType, StorageClass]], 

1174 logFailures: bool = False) -> None: 

1175 """Validate some of the configuration for this datastore. 

1176 

1177 Parameters 

1178 ---------- 

1179 entities : iterable of `DatasetRef`, `DatasetType`, or `StorageClass` 

1180 Entities to test against this configuration. Can be differing 

1181 types. 

1182 logFailures : `bool`, optional 

1183 If `True`, output a log message for every validation error 

1184 detected. 

1185 

1186 Raises 

1187 ------ 

1188 DatastoreValidationError 

1189 Raised if there is a validation problem with a configuration. 

1190 All the problems are reported in a single exception. 

1191 

1192 Notes 

1193 ----- 

1194 This method checks that all the supplied entities have valid file 

1195 templates and also have formatters defined. 

1196 """ 

1197 

1198 templateFailed = None 

1199 try: 

1200 self.templates.validateTemplates(entities, logFailures=logFailures) 

1201 except FileTemplateValidationError as e: 

1202 templateFailed = str(e) 

1203 

1204 formatterFailed = [] 

1205 for entity in entities: 

1206 try: 

1207 self.formatterFactory.getFormatterClass(entity) 

1208 except KeyError as e: 

1209 formatterFailed.append(str(e)) 

1210 if logFailures: 1210 ↛ 1205line 1210 didn't jump to line 1205, because the condition on line 1210 was never false

1211 log.fatal("Formatter failure: %s", e) 

1212 

1213 if templateFailed or formatterFailed: 

1214 messages = [] 

1215 if templateFailed: 1215 ↛ 1216line 1215 didn't jump to line 1216, because the condition on line 1215 was never true

1216 messages.append(templateFailed) 

1217 if formatterFailed: 1217 ↛ 1219line 1217 didn't jump to line 1219, because the condition on line 1217 was never false

1218 messages.append(",".join(formatterFailed)) 

1219 msg = ";\n".join(messages) 

1220 raise DatastoreValidationError(msg) 

1221 

1222 def getLookupKeys(self) -> Set[LookupKey]: 

1223 # Docstring is inherited from base class 

1224 return self.templates.getLookupKeys() | self.formatterFactory.getLookupKeys() | \ 

1225 self.constraints.getLookupKeys() 

1226 

1227 def validateKey(self, lookupKey: LookupKey, 

1228 entity: Union[DatasetRef, DatasetType, StorageClass]) -> None: 

1229 # Docstring is inherited from base class 

1230 # The key can be valid in either formatters or templates so we can 

1231 # only check the template if it exists 

1232 if lookupKey in self.templates: 

1233 try: 

1234 self.templates[lookupKey].validateTemplate(entity) 

1235 except FileTemplateValidationError as e: 

1236 raise DatastoreValidationError(e) from e