Coverage for python/lsst/daf/butler/datastores/fileDatastore.py: 84%
923 statements
« prev ^ index » next coverage.py v6.5.0, created at 2022-10-12 09:00 +0000
« prev ^ index » next coverage.py v6.5.0, created at 2022-10-12 09:00 +0000
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
23"""Generic file-based datastore code."""
25__all__ = ("FileDatastore",)
27import hashlib
28import logging
29from collections import defaultdict
30from dataclasses import dataclass
31from typing import (
32 TYPE_CHECKING,
33 Any,
34 ClassVar,
35 Dict,
36 Iterable,
37 List,
38 Mapping,
39 Optional,
40 Sequence,
41 Set,
42 Tuple,
43 Type,
44 Union,
45)
47from lsst.daf.butler import (
48 CompositesMap,
49 Config,
50 DatasetId,
51 DatasetRef,
52 DatasetRefURIs,
53 DatasetType,
54 DatasetTypeNotSupportedError,
55 Datastore,
56 DatastoreCacheManager,
57 DatastoreConfig,
58 DatastoreDisabledCacheManager,
59 DatastoreRecordData,
60 DatastoreValidationError,
61 FileDataset,
62 FileDescriptor,
63 FileTemplates,
64 FileTemplateValidationError,
65 Formatter,
66 FormatterFactory,
67 Location,
68 LocationFactory,
69 Progress,
70 StorageClass,
71 StoredDatastoreItemInfo,
72 StoredFileInfo,
73 ddl,
74)
75from lsst.daf.butler.core.repoRelocation import replaceRoot
76from lsst.daf.butler.core.utils import transactional
77from lsst.daf.butler.registry.interfaces import DatastoreRegistryBridge, ReadOnlyDatabaseError
78from lsst.resources import ResourcePath, ResourcePathExpression
79from lsst.utils.introspection import get_class_of, get_instance_of
80from lsst.utils.iteration import chunk_iterable
82# For VERBOSE logging usage.
83from lsst.utils.logging import VERBOSE, getLogger
84from lsst.utils.timer import time_this
85from sqlalchemy import BigInteger, String
87from ..registry.interfaces import FakeDatasetRef
88from .genericDatastore import GenericBaseDatastore
90if TYPE_CHECKING: 90 ↛ 91line 90 didn't jump to line 91, because the condition on line 90 was never true
91 from lsst.daf.butler import AbstractDatastoreCacheManager, LookupKey
92 from lsst.daf.butler.registry.interfaces import DatasetIdRef, DatastoreRegistryBridgeManager
94log = getLogger(__name__)
97class _IngestPrepData(Datastore.IngestPrepData):
98 """Helper class for FileDatastore ingest implementation.
100 Parameters
101 ----------
102 datasets : `list` of `FileDataset`
103 Files to be ingested by this datastore.
104 """
106 def __init__(self, datasets: List[FileDataset]):
107 super().__init__(ref for dataset in datasets for ref in dataset.refs)
108 self.datasets = datasets
111@dataclass(frozen=True)
112class DatastoreFileGetInformation:
113 """Collection of useful parameters needed to retrieve a file from
114 a Datastore.
115 """
117 location: Location
118 """The location from which to read the dataset."""
120 formatter: Formatter
121 """The `Formatter` to use to deserialize the dataset."""
123 info: StoredFileInfo
124 """Stored information about this file and its formatter."""
126 assemblerParams: Mapping[str, Any]
127 """Parameters to use for post-processing the retrieved dataset."""
129 formatterParams: Mapping[str, Any]
130 """Parameters that were understood by the associated formatter."""
132 component: Optional[str]
133 """The component to be retrieved (can be `None`)."""
135 readStorageClass: StorageClass
136 """The `StorageClass` of the dataset being read."""
139class FileDatastore(GenericBaseDatastore):
140 """Generic Datastore for file-based implementations.
142 Should always be sub-classed since key abstract methods are missing.
144 Parameters
145 ----------
146 config : `DatastoreConfig` or `str`
147 Configuration as either a `Config` object or URI to file.
148 bridgeManager : `DatastoreRegistryBridgeManager`
149 Object that manages the interface between `Registry` and datastores.
150 butlerRoot : `str`, optional
151 New datastore root to use to override the configuration value.
153 Raises
154 ------
155 ValueError
156 If root location does not exist and ``create`` is `False` in the
157 configuration.
158 """
160 defaultConfigFile: ClassVar[Optional[str]] = None
161 """Path to configuration defaults. Accessed within the ``config`` resource
162 or relative to a search path. Can be None if no defaults specified.
163 """
165 root: ResourcePath
166 """Root directory URI of this `Datastore`."""
168 locationFactory: LocationFactory
169 """Factory for creating locations relative to the datastore root."""
171 formatterFactory: FormatterFactory
172 """Factory for creating instances of formatters."""
174 templates: FileTemplates
175 """File templates that can be used by this `Datastore`."""
177 composites: CompositesMap
178 """Determines whether a dataset should be disassembled on put."""
180 defaultConfigFile = "datastores/fileDatastore.yaml"
181 """Path to configuration defaults. Accessed within the ``config`` resource
182 or relative to a search path. Can be None if no defaults specified.
183 """
185 @classmethod
186 def setConfigRoot(cls, root: str, config: Config, full: Config, overwrite: bool = True) -> None:
187 """Set any filesystem-dependent config options for this Datastore to
188 be appropriate for a new empty repository with the given root.
190 Parameters
191 ----------
192 root : `str`
193 URI to the root of the data repository.
194 config : `Config`
195 A `Config` to update. Only the subset understood by
196 this component will be updated. Will not expand
197 defaults.
198 full : `Config`
199 A complete config with all defaults expanded that can be
200 converted to a `DatastoreConfig`. Read-only and will not be
201 modified by this method.
202 Repository-specific options that should not be obtained
203 from defaults when Butler instances are constructed
204 should be copied from ``full`` to ``config``.
205 overwrite : `bool`, optional
206 If `False`, do not modify a value in ``config`` if the value
207 already exists. Default is always to overwrite with the provided
208 ``root``.
210 Notes
211 -----
212 If a keyword is explicitly defined in the supplied ``config`` it
213 will not be overridden by this method if ``overwrite`` is `False`.
214 This allows explicit values set in external configs to be retained.
215 """
216 Config.updateParameters(
217 DatastoreConfig,
218 config,
219 full,
220 toUpdate={"root": root},
221 toCopy=("cls", ("records", "table")),
222 overwrite=overwrite,
223 )
225 @classmethod
226 def makeTableSpec(cls, datasetIdColumnType: type) -> ddl.TableSpec:
227 return ddl.TableSpec(
228 fields=[
229 ddl.FieldSpec(name="dataset_id", dtype=datasetIdColumnType, primaryKey=True),
230 ddl.FieldSpec(name="path", dtype=String, length=256, nullable=False),
231 ddl.FieldSpec(name="formatter", dtype=String, length=128, nullable=False),
232 ddl.FieldSpec(name="storage_class", dtype=String, length=64, nullable=False),
233 # Use empty string to indicate no component
234 ddl.FieldSpec(name="component", dtype=String, length=32, primaryKey=True),
235 # TODO: should checksum be Base64Bytes instead?
236 ddl.FieldSpec(name="checksum", dtype=String, length=128, nullable=True),
237 ddl.FieldSpec(name="file_size", dtype=BigInteger, nullable=True),
238 ],
239 unique=frozenset(),
240 indexes=[tuple(["path"])],
241 )
243 def __init__(
244 self,
245 config: Union[DatastoreConfig, str],
246 bridgeManager: DatastoreRegistryBridgeManager,
247 butlerRoot: str = None,
248 ):
249 super().__init__(config, bridgeManager)
250 if "root" not in self.config: 250 ↛ 251line 250 didn't jump to line 251, because the condition on line 250 was never true
251 raise ValueError("No root directory specified in configuration")
253 self._bridgeManager = bridgeManager
255 # Name ourselves either using an explicit name or a name
256 # derived from the (unexpanded) root
257 if "name" in self.config:
258 self.name = self.config["name"]
259 else:
260 # We use the unexpanded root in the name to indicate that this
261 # datastore can be moved without having to update registry.
262 self.name = "{}@{}".format(type(self).__name__, self.config["root"])
264 # Support repository relocation in config
265 # Existence of self.root is checked in subclass
266 self.root = ResourcePath(
267 replaceRoot(self.config["root"], butlerRoot), forceDirectory=True, forceAbsolute=True
268 )
270 self.locationFactory = LocationFactory(self.root)
271 self.formatterFactory = FormatterFactory()
273 # Now associate formatters with storage classes
274 self.formatterFactory.registerFormatters(self.config["formatters"], universe=bridgeManager.universe)
276 # Read the file naming templates
277 self.templates = FileTemplates(self.config["templates"], universe=bridgeManager.universe)
279 # See if composites should be disassembled
280 self.composites = CompositesMap(self.config["composites"], universe=bridgeManager.universe)
282 tableName = self.config["records", "table"]
283 try:
284 # Storage of paths and formatters, keyed by dataset_id
285 self._table = bridgeManager.opaque.register(
286 tableName, self.makeTableSpec(bridgeManager.datasetIdColumnType)
287 )
288 # Interface to Registry.
289 self._bridge = bridgeManager.register(self.name)
290 except ReadOnlyDatabaseError:
291 # If the database is read only and we just tried and failed to
292 # create a table, it means someone is trying to create a read-only
293 # butler client for an empty repo. That should be okay, as long
294 # as they then try to get any datasets before some other client
295 # creates the table. Chances are they'rejust validating
296 # configuration.
297 pass
299 # Determine whether checksums should be used - default to False
300 self.useChecksum = self.config.get("checksum", False)
302 # Determine whether we can fall back to configuration if a
303 # requested dataset is not known to registry
304 self.trustGetRequest = self.config.get("trust_get_request", False)
306 # Create a cache manager
307 self.cacheManager: AbstractDatastoreCacheManager
308 if "cached" in self.config: 308 ↛ 311line 308 didn't jump to line 311, because the condition on line 308 was never false
309 self.cacheManager = DatastoreCacheManager(self.config["cached"], universe=bridgeManager.universe)
310 else:
311 self.cacheManager = DatastoreDisabledCacheManager("", universe=bridgeManager.universe)
313 # Check existence and create directory structure if necessary
314 if not self.root.exists():
315 if "create" not in self.config or not self.config["create"]: 315 ↛ 316line 315 didn't jump to line 316, because the condition on line 315 was never true
316 raise ValueError(f"No valid root and not allowed to create one at: {self.root}")
317 try:
318 self.root.mkdir()
319 except Exception as e:
320 raise ValueError(
321 f"Can not create datastore root '{self.root}', check permissions. Got error: {e}"
322 ) from e
324 def __str__(self) -> str:
325 return str(self.root)
327 @property
328 def bridge(self) -> DatastoreRegistryBridge:
329 return self._bridge
331 def _artifact_exists(self, location: Location) -> bool:
332 """Check that an artifact exists in this datastore at the specified
333 location.
335 Parameters
336 ----------
337 location : `Location`
338 Expected location of the artifact associated with this datastore.
340 Returns
341 -------
342 exists : `bool`
343 True if the location can be found, false otherwise.
344 """
345 log.debug("Checking if resource exists: %s", location.uri)
346 return location.uri.exists()
348 def _delete_artifact(self, location: Location) -> None:
349 """Delete the artifact from the datastore.
351 Parameters
352 ----------
353 location : `Location`
354 Location of the artifact associated with this datastore.
355 """
356 if location.pathInStore.isabs(): 356 ↛ 357line 356 didn't jump to line 357, because the condition on line 356 was never true
357 raise RuntimeError(f"Cannot delete artifact with absolute uri {location.uri}.")
359 try:
360 location.uri.remove()
361 except FileNotFoundError:
362 log.debug("File %s did not exist and so could not be deleted.", location.uri)
363 raise
364 except Exception as e:
365 log.critical("Failed to delete file: %s (%s)", location.uri, e)
366 raise
367 log.debug("Successfully deleted file: %s", location.uri)
369 def addStoredItemInfo(self, refs: Iterable[DatasetRef], infos: Iterable[StoredFileInfo]) -> None:
370 # Docstring inherited from GenericBaseDatastore
371 records = [info.rebase(ref).to_record() for ref, info in zip(refs, infos)]
372 self._table.insert(*records)
374 def getStoredItemsInfo(self, ref: DatasetIdRef) -> List[StoredFileInfo]:
375 # Docstring inherited from GenericBaseDatastore
377 # Look for the dataset_id -- there might be multiple matches
378 # if we have disassembled the dataset.
379 records = self._table.fetch(dataset_id=ref.id)
380 return [StoredFileInfo.from_record(record) for record in records]
382 def _get_stored_records_associated_with_refs(
383 self, refs: Iterable[DatasetIdRef]
384 ) -> Dict[DatasetId, List[StoredFileInfo]]:
385 """Retrieve all records associated with the provided refs.
387 Parameters
388 ----------
389 refs : iterable of `DatasetIdRef`
390 The refs for which records are to be retrieved.
392 Returns
393 -------
394 records : `dict` of [`DatasetId`, `list` of `StoredFileInfo`]
395 The matching records indexed by the ref ID. The number of entries
396 in the dict can be smaller than the number of requested refs.
397 """
398 records = self._table.fetch(dataset_id=[ref.id for ref in refs])
400 # Uniqueness is dataset_id + component so can have multiple records
401 # per ref.
402 records_by_ref = defaultdict(list)
403 for record in records:
404 records_by_ref[record["dataset_id"]].append(StoredFileInfo.from_record(record))
405 return records_by_ref
407 def _refs_associated_with_artifacts(
408 self, paths: List[Union[str, ResourcePath]]
409 ) -> Dict[str, Set[DatasetId]]:
410 """Return paths and associated dataset refs.
412 Parameters
413 ----------
414 paths : `list` of `str` or `lsst.resources.ResourcePath`
415 All the paths to include in search.
417 Returns
418 -------
419 mapping : `dict` of [`str`, `set` [`DatasetId`]]
420 Mapping of each path to a set of associated database IDs.
421 """
422 records = self._table.fetch(path=[str(path) for path in paths])
423 result = defaultdict(set)
424 for row in records:
425 result[row["path"]].add(row["dataset_id"])
426 return result
428 def _registered_refs_per_artifact(self, pathInStore: ResourcePath) -> Set[DatasetId]:
429 """Return all dataset refs associated with the supplied path.
431 Parameters
432 ----------
433 pathInStore : `lsst.resources.ResourcePath`
434 Path of interest in the data store.
436 Returns
437 -------
438 ids : `set` of `int`
439 All `DatasetRef` IDs associated with this path.
440 """
441 records = list(self._table.fetch(path=str(pathInStore)))
442 ids = {r["dataset_id"] for r in records}
443 return ids
445 def removeStoredItemInfo(self, ref: DatasetIdRef) -> None:
446 # Docstring inherited from GenericBaseDatastore
447 self._table.delete(["dataset_id"], {"dataset_id": ref.id})
449 def _get_dataset_locations_info(self, ref: DatasetIdRef) -> List[Tuple[Location, StoredFileInfo]]:
450 r"""Find all the `Location`\ s of the requested dataset in the
451 `Datastore` and the associated stored file information.
453 Parameters
454 ----------
455 ref : `DatasetRef`
456 Reference to the required `Dataset`.
458 Returns
459 -------
460 results : `list` [`tuple` [`Location`, `StoredFileInfo` ]]
461 Location of the dataset within the datastore and
462 stored information about each file and its formatter.
463 """
464 # Get the file information (this will fail if no file)
465 records = self.getStoredItemsInfo(ref)
467 # Use the path to determine the location -- we need to take
468 # into account absolute URIs in the datastore record
469 return [(r.file_location(self.locationFactory), r) for r in records]
471 def _can_remove_dataset_artifact(self, ref: DatasetIdRef, location: Location) -> bool:
472 """Check that there is only one dataset associated with the
473 specified artifact.
475 Parameters
476 ----------
477 ref : `DatasetRef` or `FakeDatasetRef`
478 Dataset to be removed.
479 location : `Location`
480 The location of the artifact to be removed.
482 Returns
483 -------
484 can_remove : `Bool`
485 True if the artifact can be safely removed.
486 """
487 # Can't ever delete absolute URIs.
488 if location.pathInStore.isabs():
489 return False
491 # Get all entries associated with this path
492 allRefs = self._registered_refs_per_artifact(location.pathInStore)
493 if not allRefs:
494 raise RuntimeError(f"Datastore inconsistency error. {location.pathInStore} not in registry")
496 # Remove these refs from all the refs and if there is nothing left
497 # then we can delete
498 remainingRefs = allRefs - {ref.id}
500 if remainingRefs:
501 return False
502 return True
504 def _get_expected_dataset_locations_info(self, ref: DatasetRef) -> List[Tuple[Location, StoredFileInfo]]:
505 """Predict the location and related file information of the requested
506 dataset in this datastore.
508 Parameters
509 ----------
510 ref : `DatasetRef`
511 Reference to the required `Dataset`.
513 Returns
514 -------
515 results : `list` [`tuple` [`Location`, `StoredFileInfo` ]]
516 Expected Location of the dataset within the datastore and
517 placeholder information about each file and its formatter.
519 Notes
520 -----
521 Uses the current configuration to determine how we would expect the
522 datastore files to have been written if we couldn't ask registry.
523 This is safe so long as there has been no change to datastore
524 configuration between writing the dataset and wanting to read it.
525 Will not work for files that have been ingested without using the
526 standard file template or default formatter.
527 """
529 # If we have a component ref we always need to ask the questions
530 # of the composite. If the composite is disassembled this routine
531 # should return all components. If the composite was not
532 # disassembled the composite is what is stored regardless of
533 # component request. Note that if the caller has disassembled
534 # a composite there is no way for this guess to know that
535 # without trying both the composite and component ref and seeing
536 # if there is something at the component Location even without
537 # disassembly being enabled.
538 if ref.datasetType.isComponent():
539 ref = ref.makeCompositeRef()
541 # See if the ref is a composite that should be disassembled
542 doDisassembly = self.composites.shouldBeDisassembled(ref)
544 all_info: List[Tuple[Location, Formatter, StorageClass, Optional[str]]] = []
546 if doDisassembly:
547 for component, componentStorage in ref.datasetType.storageClass.components.items():
548 compRef = ref.makeComponentRef(component)
549 location, formatter = self._determine_put_formatter_location(compRef)
550 all_info.append((location, formatter, componentStorage, component))
552 else:
553 # Always use the composite ref if no disassembly
554 location, formatter = self._determine_put_formatter_location(ref)
555 all_info.append((location, formatter, ref.datasetType.storageClass, None))
557 # Convert the list of tuples to have StoredFileInfo as second element
558 return [
559 (
560 location,
561 StoredFileInfo(
562 formatter=formatter,
563 path=location.pathInStore.path,
564 storageClass=storageClass,
565 component=component,
566 checksum=None,
567 file_size=-1,
568 dataset_id=ref.getCheckedId(),
569 ),
570 )
571 for location, formatter, storageClass, component in all_info
572 ]
574 def _prepare_for_get(
575 self, ref: DatasetRef, parameters: Optional[Mapping[str, Any]] = None
576 ) -> List[DatastoreFileGetInformation]:
577 """Check parameters for ``get`` and obtain formatter and
578 location.
580 Parameters
581 ----------
582 ref : `DatasetRef`
583 Reference to the required Dataset.
584 parameters : `dict`
585 `StorageClass`-specific parameters that specify, for example,
586 a slice of the dataset to be loaded.
588 Returns
589 -------
590 getInfo : `list` [`DatastoreFileGetInformation`]
591 Parameters needed to retrieve each file.
592 """
593 log.debug("Retrieve %s from %s with parameters %s", ref, self.name, parameters)
595 # Get file metadata and internal metadata
596 fileLocations = self._get_dataset_locations_info(ref)
597 if not fileLocations:
598 if not self.trustGetRequest:
599 raise FileNotFoundError(f"Could not retrieve dataset {ref}.")
600 # Assume the dataset is where we think it should be
601 fileLocations = self._get_expected_dataset_locations_info(ref)
603 # The storage class we want to use eventually
604 refStorageClass = ref.datasetType.storageClass
606 if len(fileLocations) > 1:
607 disassembled = True
609 # If trust is involved it is possible that there will be
610 # components listed here that do not exist in the datastore.
611 # Explicitly check for file artifact existence and filter out any
612 # that are missing.
613 if self.trustGetRequest:
614 fileLocations = [loc for loc in fileLocations if loc[0].uri.exists()]
616 # For now complain only if we have no components at all. One
617 # component is probably a problem but we can punt that to the
618 # assembler.
619 if not fileLocations: 619 ↛ 620line 619 didn't jump to line 620, because the condition on line 619 was never true
620 raise FileNotFoundError(f"None of the component files for dataset {ref} exist.")
622 else:
623 disassembled = False
625 # Is this a component request?
626 refComponent = ref.datasetType.component()
628 fileGetInfo = []
629 for location, storedFileInfo in fileLocations:
631 # The storage class used to write the file
632 writeStorageClass = storedFileInfo.storageClass
634 # If this has been disassembled we need read to match the write
635 if disassembled:
636 readStorageClass = writeStorageClass
637 else:
638 readStorageClass = refStorageClass
640 formatter = get_instance_of(
641 storedFileInfo.formatter,
642 FileDescriptor(
643 location,
644 readStorageClass=readStorageClass,
645 storageClass=writeStorageClass,
646 parameters=parameters,
647 ),
648 ref.dataId,
649 )
651 formatterParams, notFormatterParams = formatter.segregateParameters()
653 # Of the remaining parameters, extract the ones supported by
654 # this StorageClass (for components not all will be handled)
655 assemblerParams = readStorageClass.filterParameters(notFormatterParams)
657 # The ref itself could be a component if the dataset was
658 # disassembled by butler, or we disassembled in datastore and
659 # components came from the datastore records
660 component = storedFileInfo.component if storedFileInfo.component else refComponent
662 fileGetInfo.append(
663 DatastoreFileGetInformation(
664 location,
665 formatter,
666 storedFileInfo,
667 assemblerParams,
668 formatterParams,
669 component,
670 readStorageClass,
671 )
672 )
674 return fileGetInfo
676 def _prepare_for_put(self, inMemoryDataset: Any, ref: DatasetRef) -> Tuple[Location, Formatter]:
677 """Check the arguments for ``put`` and obtain formatter and
678 location.
680 Parameters
681 ----------
682 inMemoryDataset : `object`
683 The dataset to store.
684 ref : `DatasetRef`
685 Reference to the associated Dataset.
687 Returns
688 -------
689 location : `Location`
690 The location to write the dataset.
691 formatter : `Formatter`
692 The `Formatter` to use to write the dataset.
694 Raises
695 ------
696 TypeError
697 Supplied object and storage class are inconsistent.
698 DatasetTypeNotSupportedError
699 The associated `DatasetType` is not handled by this datastore.
700 """
701 self._validate_put_parameters(inMemoryDataset, ref)
702 return self._determine_put_formatter_location(ref)
704 def _determine_put_formatter_location(self, ref: DatasetRef) -> Tuple[Location, Formatter]:
705 """Calculate the formatter and output location to use for put.
707 Parameters
708 ----------
709 ref : `DatasetRef`
710 Reference to the associated Dataset.
712 Returns
713 -------
714 location : `Location`
715 The location to write the dataset.
716 formatter : `Formatter`
717 The `Formatter` to use to write the dataset.
718 """
719 # Work out output file name
720 try:
721 template = self.templates.getTemplate(ref)
722 except KeyError as e:
723 raise DatasetTypeNotSupportedError(f"Unable to find template for {ref}") from e
725 # Validate the template to protect against filenames from different
726 # dataIds returning the same and causing overwrite confusion.
727 template.validateTemplate(ref)
729 location = self.locationFactory.fromPath(template.format(ref))
731 # Get the formatter based on the storage class
732 storageClass = ref.datasetType.storageClass
733 try:
734 formatter = self.formatterFactory.getFormatter(
735 ref, FileDescriptor(location, storageClass=storageClass), ref.dataId
736 )
737 except KeyError as e:
738 raise DatasetTypeNotSupportedError(
739 f"Unable to find formatter for {ref} in datastore {self.name}"
740 ) from e
742 # Now that we know the formatter, update the location
743 location = formatter.makeUpdatedLocation(location)
745 return location, formatter
747 def _overrideTransferMode(self, *datasets: FileDataset, transfer: Optional[str] = None) -> Optional[str]:
748 # Docstring inherited from base class
749 if transfer != "auto":
750 return transfer
752 # See if the paths are within the datastore or not
753 inside = [self._pathInStore(d.path) is not None for d in datasets]
755 if all(inside):
756 transfer = None
757 elif not any(inside): 757 ↛ 766line 757 didn't jump to line 766, because the condition on line 757 was never false
758 # Allow ResourcePath to use its own knowledge
759 transfer = "auto"
760 else:
761 # This can happen when importing from a datastore that
762 # has had some datasets ingested using "direct" mode.
763 # Also allow ResourcePath to sort it out but warn about it.
764 # This can happen if you are importing from a datastore
765 # that had some direct transfer datasets.
766 log.warning(
767 "Some datasets are inside the datastore and some are outside. Using 'split' "
768 "transfer mode. This assumes that the files outside the datastore are "
769 "still accessible to the new butler since they will not be copied into "
770 "the target datastore."
771 )
772 transfer = "split"
774 return transfer
776 def _pathInStore(self, path: ResourcePathExpression) -> Optional[str]:
777 """Return path relative to datastore root
779 Parameters
780 ----------
781 path : `lsst.resources.ResourcePathExpression`
782 Path to dataset. Can be absolute URI. If relative assumed to
783 be relative to the datastore. Returns path in datastore
784 or raises an exception if the path it outside.
786 Returns
787 -------
788 inStore : `str`
789 Path relative to datastore root. Returns `None` if the file is
790 outside the root.
791 """
792 # Relative path will always be relative to datastore
793 pathUri = ResourcePath(path, forceAbsolute=False)
794 return pathUri.relative_to(self.root)
796 def _standardizeIngestPath(
797 self, path: Union[str, ResourcePath], *, transfer: Optional[str] = None
798 ) -> Union[str, ResourcePath]:
799 """Standardize the path of a to-be-ingested file.
801 Parameters
802 ----------
803 path : `str` or `lsst.resources.ResourcePath`
804 Path of a file to be ingested. This parameter is not expected
805 to be all the types that can be used to construct a
806 `~lsst.resources.ResourcePath`.
807 transfer : `str`, optional
808 How (and whether) the dataset should be added to the datastore.
809 See `ingest` for details of transfer modes.
810 This implementation is provided only so
811 `NotImplementedError` can be raised if the mode is not supported;
812 actual transfers are deferred to `_extractIngestInfo`.
814 Returns
815 -------
816 path : `str` or `lsst.resources.ResourcePath`
817 New path in what the datastore considers standard form. If an
818 absolute URI was given that will be returned unchanged.
820 Notes
821 -----
822 Subclasses of `FileDatastore` can implement this method instead
823 of `_prepIngest`. It should not modify the data repository or given
824 file in any way.
826 Raises
827 ------
828 NotImplementedError
829 Raised if the datastore does not support the given transfer mode
830 (including the case where ingest is not supported at all).
831 FileNotFoundError
832 Raised if one of the given files does not exist.
833 """
834 if transfer not in (None, "direct", "split") + self.root.transferModes: 834 ↛ 835line 834 didn't jump to line 835, because the condition on line 834 was never true
835 raise NotImplementedError(f"Transfer mode {transfer} not supported.")
837 # A relative URI indicates relative to datastore root
838 srcUri = ResourcePath(path, forceAbsolute=False)
839 if not srcUri.isabs():
840 srcUri = self.root.join(path)
842 if not srcUri.exists():
843 raise FileNotFoundError(
844 f"Resource at {srcUri} does not exist; note that paths to ingest "
845 f"are assumed to be relative to {self.root} unless they are absolute."
846 )
848 if transfer is None:
849 relpath = srcUri.relative_to(self.root)
850 if not relpath:
851 raise RuntimeError(
852 f"Transfer is none but source file ({srcUri}) is not within datastore ({self.root})"
853 )
855 # Return the relative path within the datastore for internal
856 # transfer
857 path = relpath
859 return path
861 def _extractIngestInfo(
862 self,
863 path: ResourcePathExpression,
864 ref: DatasetRef,
865 *,
866 formatter: Union[Formatter, Type[Formatter]],
867 transfer: Optional[str] = None,
868 record_validation_info: bool = True,
869 ) -> StoredFileInfo:
870 """Relocate (if necessary) and extract `StoredFileInfo` from a
871 to-be-ingested file.
873 Parameters
874 ----------
875 path : `lsst.resources.ResourcePathExpression`
876 URI or path of a file to be ingested.
877 ref : `DatasetRef`
878 Reference for the dataset being ingested. Guaranteed to have
879 ``dataset_id not None`.
880 formatter : `type` or `Formatter`
881 `Formatter` subclass to use for this dataset or an instance.
882 transfer : `str`, optional
883 How (and whether) the dataset should be added to the datastore.
884 See `ingest` for details of transfer modes.
885 record_validation_info : `bool`, optional
886 If `True`, the default, the datastore can record validation
887 information associated with the file. If `False` the datastore
888 will not attempt to track any information such as checksums
889 or file sizes. This can be useful if such information is tracked
890 in an external system or if the file is to be compressed in place.
891 It is up to the datastore whether this parameter is relevant.
893 Returns
894 -------
895 info : `StoredFileInfo`
896 Internal datastore record for this file. This will be inserted by
897 the caller; the `_extractIngestInfo` is only responsible for
898 creating and populating the struct.
900 Raises
901 ------
902 FileNotFoundError
903 Raised if one of the given files does not exist.
904 FileExistsError
905 Raised if transfer is not `None` but the (internal) location the
906 file would be moved to is already occupied.
907 """
908 if self._transaction is None: 908 ↛ 909line 908 didn't jump to line 909, because the condition on line 908 was never true
909 raise RuntimeError("Ingest called without transaction enabled")
911 # Create URI of the source path, do not need to force a relative
912 # path to absolute.
913 srcUri = ResourcePath(path, forceAbsolute=False)
915 # Track whether we have read the size of the source yet
916 have_sized = False
918 tgtLocation: Optional[Location]
919 if transfer is None or transfer == "split":
920 # A relative path is assumed to be relative to the datastore
921 # in this context
922 if not srcUri.isabs():
923 tgtLocation = self.locationFactory.fromPath(srcUri.ospath)
924 else:
925 # Work out the path in the datastore from an absolute URI
926 # This is required to be within the datastore.
927 pathInStore = srcUri.relative_to(self.root)
928 if pathInStore is None and transfer is None: 928 ↛ 929line 928 didn't jump to line 929, because the condition on line 928 was never true
929 raise RuntimeError(
930 f"Unexpectedly learned that {srcUri} is not within datastore {self.root}"
931 )
932 if pathInStore: 932 ↛ 934line 932 didn't jump to line 934, because the condition on line 932 was never false
933 tgtLocation = self.locationFactory.fromPath(pathInStore)
934 elif transfer == "split":
935 # Outside the datastore but treat that as a direct ingest
936 # instead.
937 tgtLocation = None
938 else:
939 raise RuntimeError(f"Unexpected transfer mode encountered: {transfer} for URI {srcUri}")
940 elif transfer == "direct": 940 ↛ 945line 940 didn't jump to line 945, because the condition on line 940 was never true
941 # Want to store the full URI to the resource directly in
942 # datastore. This is useful for referring to permanent archive
943 # storage for raw data.
944 # Trust that people know what they are doing.
945 tgtLocation = None
946 else:
947 # Work out the name we want this ingested file to have
948 # inside the datastore
949 tgtLocation = self._calculate_ingested_datastore_name(srcUri, ref, formatter)
950 if not tgtLocation.uri.dirname().exists():
951 log.debug("Folder %s does not exist yet.", tgtLocation.uri.dirname())
952 tgtLocation.uri.dirname().mkdir()
954 # if we are transferring from a local file to a remote location
955 # it may be more efficient to get the size and checksum of the
956 # local file rather than the transferred one
957 if record_validation_info and srcUri.isLocal:
958 size = srcUri.size()
959 checksum = self.computeChecksum(srcUri) if self.useChecksum else None
960 have_sized = True
962 # Transfer the resource to the destination.
963 # Allow overwrite of an existing file. This matches the behavior
964 # of datastore.put() in that it trusts that registry would not
965 # be asking to overwrite unless registry thought that the
966 # overwrite was allowed.
967 tgtLocation.uri.transfer_from(
968 srcUri, transfer=transfer, transaction=self._transaction, overwrite=True
969 )
971 if tgtLocation is None: 971 ↛ 973line 971 didn't jump to line 973, because the condition on line 971 was never true
972 # This means we are using direct mode
973 targetUri = srcUri
974 targetPath = str(srcUri)
975 else:
976 targetUri = tgtLocation.uri
977 targetPath = tgtLocation.pathInStore.path
979 # the file should exist in the datastore now
980 if record_validation_info:
981 if not have_sized:
982 size = targetUri.size()
983 checksum = self.computeChecksum(targetUri) if self.useChecksum else None
984 else:
985 # Not recording any file information.
986 size = -1
987 checksum = None
989 return StoredFileInfo(
990 formatter=formatter,
991 path=targetPath,
992 storageClass=ref.datasetType.storageClass,
993 component=ref.datasetType.component(),
994 file_size=size,
995 checksum=checksum,
996 dataset_id=ref.getCheckedId(),
997 )
999 def _prepIngest(self, *datasets: FileDataset, transfer: Optional[str] = None) -> _IngestPrepData:
1000 # Docstring inherited from Datastore._prepIngest.
1001 filtered = []
1002 for dataset in datasets:
1003 acceptable = [ref for ref in dataset.refs if self.constraints.isAcceptable(ref)]
1004 if not acceptable:
1005 continue
1006 else:
1007 dataset.refs = acceptable
1008 if dataset.formatter is None:
1009 dataset.formatter = self.formatterFactory.getFormatterClass(dataset.refs[0])
1010 else:
1011 assert isinstance(dataset.formatter, (type, str))
1012 formatter_class = get_class_of(dataset.formatter)
1013 if not issubclass(formatter_class, Formatter): 1013 ↛ 1014line 1013 didn't jump to line 1014, because the condition on line 1013 was never true
1014 raise TypeError(f"Requested formatter {dataset.formatter} is not a Formatter class.")
1015 dataset.formatter = formatter_class
1016 dataset.path = self._standardizeIngestPath(dataset.path, transfer=transfer)
1017 filtered.append(dataset)
1018 return _IngestPrepData(filtered)
1020 @transactional
1021 def _finishIngest(
1022 self,
1023 prepData: Datastore.IngestPrepData,
1024 *,
1025 transfer: Optional[str] = None,
1026 record_validation_info: bool = True,
1027 ) -> None:
1028 # Docstring inherited from Datastore._finishIngest.
1029 refsAndInfos = []
1030 progress = Progress("lsst.daf.butler.datastores.FileDatastore.ingest", level=logging.DEBUG)
1031 for dataset in progress.wrap(prepData.datasets, desc="Ingesting dataset files"):
1032 # Do ingest as if the first dataset ref is associated with the file
1033 info = self._extractIngestInfo(
1034 dataset.path,
1035 dataset.refs[0],
1036 formatter=dataset.formatter,
1037 transfer=transfer,
1038 record_validation_info=record_validation_info,
1039 )
1040 refsAndInfos.extend([(ref, info) for ref in dataset.refs])
1041 self._register_datasets(refsAndInfos)
1043 def _calculate_ingested_datastore_name(
1044 self, srcUri: ResourcePath, ref: DatasetRef, formatter: Union[Formatter, Type[Formatter]]
1045 ) -> Location:
1046 """Given a source URI and a DatasetRef, determine the name the
1047 dataset will have inside datastore.
1049 Parameters
1050 ----------
1051 srcUri : `lsst.resources.ResourcePath`
1052 URI to the source dataset file.
1053 ref : `DatasetRef`
1054 Ref associated with the newly-ingested dataset artifact. This
1055 is used to determine the name within the datastore.
1056 formatter : `Formatter` or Formatter class.
1057 Formatter to use for validation. Can be a class or an instance.
1059 Returns
1060 -------
1061 location : `Location`
1062 Target location for the newly-ingested dataset.
1063 """
1064 # Ingesting a file from outside the datastore.
1065 # This involves a new name.
1066 template = self.templates.getTemplate(ref)
1067 location = self.locationFactory.fromPath(template.format(ref))
1069 # Get the extension
1070 ext = srcUri.getExtension()
1072 # Update the destination to include that extension
1073 location.updateExtension(ext)
1075 # Ask the formatter to validate this extension
1076 formatter.validateExtension(location)
1078 return location
1080 def _write_in_memory_to_artifact(self, inMemoryDataset: Any, ref: DatasetRef) -> StoredFileInfo:
1081 """Write out in memory dataset to datastore.
1083 Parameters
1084 ----------
1085 inMemoryDataset : `object`
1086 Dataset to write to datastore.
1087 ref : `DatasetRef`
1088 Registry information associated with this dataset.
1090 Returns
1091 -------
1092 info : `StoredFileInfo`
1093 Information describing the artifact written to the datastore.
1094 """
1095 # May need to coerce the in memory dataset to the correct
1096 # python type.
1097 inMemoryDataset = ref.datasetType.storageClass.coerce_type(inMemoryDataset)
1099 location, formatter = self._prepare_for_put(inMemoryDataset, ref)
1100 uri = location.uri
1102 if not uri.dirname().exists():
1103 log.debug("Folder %s does not exist yet so creating it.", uri.dirname())
1104 uri.dirname().mkdir()
1106 if self._transaction is None: 1106 ↛ 1107line 1106 didn't jump to line 1107, because the condition on line 1106 was never true
1107 raise RuntimeError("Attempting to write artifact without transaction enabled")
1109 def _removeFileExists(uri: ResourcePath) -> None:
1110 """Remove a file and do not complain if it is not there.
1112 This is important since a formatter might fail before the file
1113 is written and we should not confuse people by writing spurious
1114 error messages to the log.
1115 """
1116 try:
1117 uri.remove()
1118 except FileNotFoundError:
1119 pass
1121 # Register a callback to try to delete the uploaded data if
1122 # something fails below
1123 self._transaction.registerUndo("artifactWrite", _removeFileExists, uri)
1125 data_written = False
1126 if not uri.isLocal:
1127 # This is a remote URI. Some datasets can be serialized directly
1128 # to bytes and sent to the remote datastore without writing a
1129 # file. If the dataset is intended to be saved to the cache
1130 # a file is always written and direct write to the remote
1131 # datastore is bypassed.
1132 if not self.cacheManager.should_be_cached(ref):
1133 try:
1134 serializedDataset = formatter.toBytes(inMemoryDataset)
1135 except NotImplementedError:
1136 # Fallback to the file writing option.
1137 pass
1138 except Exception as e:
1139 raise RuntimeError(
1140 f"Failed to serialize dataset {ref} of type {type(inMemoryDataset)} to bytes."
1141 ) from e
1142 else:
1143 log.debug("Writing bytes directly to %s", uri)
1144 uri.write(serializedDataset, overwrite=True)
1145 log.debug("Successfully wrote bytes directly to %s", uri)
1146 data_written = True
1148 if not data_written:
1149 # Did not write the bytes directly to object store so instead
1150 # write to temporary file. Always write to a temporary even if
1151 # using a local file system -- that gives us atomic writes.
1152 # If a process is killed as the file is being written we do not
1153 # want it to remain in the correct place but in corrupt state.
1154 # For local files write to the output directory not temporary dir.
1155 prefix = uri.dirname() if uri.isLocal else None
1156 with ResourcePath.temporary_uri(suffix=uri.getExtension(), prefix=prefix) as temporary_uri:
1157 # Need to configure the formatter to write to a different
1158 # location and that needs us to overwrite internals
1159 log.debug("Writing dataset to temporary location at %s", temporary_uri)
1160 with formatter._updateLocation(Location(None, temporary_uri)):
1161 try:
1162 formatter.write(inMemoryDataset)
1163 except Exception as e:
1164 raise RuntimeError(
1165 f"Failed to serialize dataset {ref} of type"
1166 f" {type(inMemoryDataset)} to "
1167 f"temporary location {temporary_uri}"
1168 ) from e
1170 # Use move for a local file since that becomes an efficient
1171 # os.rename. For remote resources we use copy to allow the
1172 # file to be cached afterwards.
1173 transfer = "move" if uri.isLocal else "copy"
1175 uri.transfer_from(temporary_uri, transfer=transfer, overwrite=True)
1177 if transfer == "copy":
1178 # Cache if required
1179 self.cacheManager.move_to_cache(temporary_uri, ref)
1181 log.debug("Successfully wrote dataset to %s via a temporary file.", uri)
1183 # URI is needed to resolve what ingest case are we dealing with
1184 return self._extractIngestInfo(uri, ref, formatter=formatter)
1186 def _read_artifact_into_memory(
1187 self,
1188 getInfo: DatastoreFileGetInformation,
1189 ref: DatasetRef,
1190 isComponent: bool = False,
1191 cache_ref: Optional[DatasetRef] = None,
1192 ) -> Any:
1193 """Read the artifact from datastore into in memory object.
1195 Parameters
1196 ----------
1197 getInfo : `DatastoreFileGetInformation`
1198 Information about the artifact within the datastore.
1199 ref : `DatasetRef`
1200 The registry information associated with this artifact.
1201 isComponent : `bool`
1202 Flag to indicate if a component is being read from this artifact.
1203 cache_ref : `DatasetRef`, optional
1204 The DatasetRef to use when looking up the file in the cache.
1205 This ref must have the same ID as the supplied ref but can
1206 be a parent ref or component ref to indicate to the cache whether
1207 a composite file is being requested from the cache or a component
1208 file. Without this the cache will default to the supplied ref but
1209 it can get confused with read-only derived components for
1210 disassembled composites.
1212 Returns
1213 -------
1214 inMemoryDataset : `object`
1215 The artifact as a python object.
1216 """
1217 location = getInfo.location
1218 uri = location.uri
1219 log.debug("Accessing data from %s", uri)
1221 if cache_ref is None:
1222 cache_ref = ref
1223 if cache_ref.id != ref.id: 1223 ↛ 1224line 1223 didn't jump to line 1224, because the condition on line 1223 was never true
1224 raise ValueError(
1225 "The supplied cache dataset ref refers to a different dataset than expected:"
1226 f" {ref.id} != {cache_ref.id}"
1227 )
1229 # Cannot recalculate checksum but can compare size as a quick check
1230 # Do not do this if the size is negative since that indicates
1231 # we do not know.
1232 recorded_size = getInfo.info.file_size
1233 resource_size = uri.size()
1234 if recorded_size >= 0 and resource_size != recorded_size: 1234 ↛ 1235line 1234 didn't jump to line 1235, because the condition on line 1234 was never true
1235 raise RuntimeError(
1236 "Integrity failure in Datastore. "
1237 f"Size of file {uri} ({resource_size}) "
1238 f"does not match size recorded in registry of {recorded_size}"
1239 )
1241 # For the general case we have choices for how to proceed.
1242 # 1. Always use a local file (downloading the remote resource to a
1243 # temporary file if needed).
1244 # 2. Use a threshold size and read into memory and use bytes.
1245 # Use both for now with an arbitrary hand off size.
1246 # This allows small datasets to be downloaded from remote object
1247 # stores without requiring a temporary file.
1249 formatter = getInfo.formatter
1250 nbytes_max = 10_000_000 # Arbitrary number that we can tune
1251 if resource_size <= nbytes_max and formatter.can_read_bytes():
1252 with self.cacheManager.find_in_cache(cache_ref, uri.getExtension()) as cached_file:
1253 if cached_file is not None:
1254 desired_uri = cached_file
1255 msg = f" (cached version of {uri})"
1256 else:
1257 desired_uri = uri
1258 msg = ""
1259 with time_this(log, msg="Reading bytes from %s%s", args=(desired_uri, msg)):
1260 serializedDataset = desired_uri.read()
1261 log.debug(
1262 "Deserializing %s from %d bytes from location %s with formatter %s",
1263 f"component {getInfo.component}" if isComponent else "",
1264 len(serializedDataset),
1265 uri,
1266 formatter.name(),
1267 )
1268 try:
1269 result = formatter.fromBytes(
1270 serializedDataset, component=getInfo.component if isComponent else None
1271 )
1272 except Exception as e:
1273 raise ValueError(
1274 f"Failure from formatter '{formatter.name()}' for dataset {ref.id}"
1275 f" ({ref.datasetType.name} from {uri}): {e}"
1276 ) from e
1277 else:
1278 # Read from file.
1280 # Have to update the Location associated with the formatter
1281 # because formatter.read does not allow an override.
1282 # This could be improved.
1283 location_updated = False
1284 msg = ""
1286 # First check in cache for local version.
1287 # The cache will only be relevant for remote resources but
1288 # no harm in always asking. Context manager ensures that cache
1289 # file is not deleted during cache expiration.
1290 with self.cacheManager.find_in_cache(cache_ref, uri.getExtension()) as cached_file:
1291 if cached_file is not None:
1292 msg = f"(via cache read of remote file {uri})"
1293 uri = cached_file
1294 location_updated = True
1296 with uri.as_local() as local_uri:
1298 can_be_cached = False
1299 if uri != local_uri: 1299 ↛ 1301line 1299 didn't jump to line 1301, because the condition on line 1299 was never true
1300 # URI was remote and file was downloaded
1301 cache_msg = ""
1302 location_updated = True
1304 if self.cacheManager.should_be_cached(cache_ref):
1305 # In this scenario we want to ask if the downloaded
1306 # file should be cached but we should not cache
1307 # it until after we've used it (to ensure it can't
1308 # be expired whilst we are using it).
1309 can_be_cached = True
1311 # Say that it is "likely" to be cached because
1312 # if the formatter read fails we will not be
1313 # caching this file.
1314 cache_msg = " and likely cached"
1316 msg = f"(via download to local file{cache_msg})"
1318 # Calculate the (possibly) new location for the formatter
1319 # to use.
1320 newLocation = Location(*local_uri.split()) if location_updated else None
1322 log.debug(
1323 "Reading%s from location %s %s with formatter %s",
1324 f" component {getInfo.component}" if isComponent else "",
1325 uri,
1326 msg,
1327 formatter.name(),
1328 )
1329 try:
1330 with formatter._updateLocation(newLocation):
1331 with time_this(
1332 log,
1333 msg="Reading%s from location %s %s with formatter %s",
1334 args=(
1335 f" component {getInfo.component}" if isComponent else "",
1336 uri,
1337 msg,
1338 formatter.name(),
1339 ),
1340 ):
1341 result = formatter.read(component=getInfo.component if isComponent else None)
1342 except Exception as e:
1343 raise ValueError(
1344 f"Failure from formatter '{formatter.name()}' for dataset {ref.id}"
1345 f" ({ref.datasetType.name} from {uri}): {e}"
1346 ) from e
1348 # File was read successfully so can move to cache
1349 if can_be_cached: 1349 ↛ 1350line 1349 didn't jump to line 1350, because the condition on line 1349 was never true
1350 self.cacheManager.move_to_cache(local_uri, cache_ref)
1352 return self._post_process_get(
1353 result, getInfo.readStorageClass, getInfo.assemblerParams, isComponent=isComponent
1354 )
1356 def knows(self, ref: DatasetRef) -> bool:
1357 """Check if the dataset is known to the datastore.
1359 Does not check for existence of any artifact.
1361 Parameters
1362 ----------
1363 ref : `DatasetRef`
1364 Reference to the required dataset.
1366 Returns
1367 -------
1368 exists : `bool`
1369 `True` if the dataset is known to the datastore.
1370 """
1371 fileLocations = self._get_dataset_locations_info(ref)
1372 if fileLocations:
1373 return True
1374 return False
1376 def _process_mexists_records(
1377 self,
1378 id_to_ref: Dict[DatasetId, DatasetRef],
1379 records: Dict[DatasetId, List[StoredFileInfo]],
1380 all_required: bool,
1381 artifact_existence: Optional[Dict[ResourcePath, bool]] = None,
1382 ) -> Dict[DatasetRef, bool]:
1383 """Helper function for mexists that checks the given records.
1385 Parameters
1386 ----------
1387 id_to_ref : `dict` of [`DatasetId`, `DatasetRef`]
1388 Mapping of the dataset ID to the dataset ref itself.
1389 records : `dict` of [`DatasetId`, `list` of `StoredFileInfo`]
1390 Records as generally returned by
1391 ``_get_stored_records_associated_with_refs``.
1392 all_required : `bool`
1393 Flag to indicate whether existence requires all artifacts
1394 associated with a dataset ID to exist or not for existence.
1395 artifact_existence : `dict` [`lsst.resources.ResourcePath`, `bool`]
1396 Optional mapping of datastore artifact to existence. Updated by
1397 this method with details of all artifacts tested. Can be `None`
1398 if the caller is not interested.
1400 Returns
1401 -------
1402 existence : `dict` of [`DatasetRef`, `bool`]
1403 Mapping from dataset to boolean indicating existence.
1404 """
1405 # The URIs to be checked and a mapping of those URIs to
1406 # the dataset ID.
1407 uris_to_check: List[ResourcePath] = []
1408 location_map: Dict[ResourcePath, DatasetId] = {}
1410 location_factory = self.locationFactory
1412 uri_existence: Dict[ResourcePath, bool] = {}
1413 for ref_id, infos in records.items():
1414 # Key is the dataset Id, value is list of StoredItemInfo
1415 uris = [info.file_location(location_factory).uri for info in infos]
1416 location_map.update({uri: ref_id for uri in uris})
1418 # Check the local cache directly for a dataset corresponding
1419 # to the remote URI.
1420 if self.cacheManager.file_count > 0: 1420 ↛ 1421line 1420 didn't jump to line 1421, because the condition on line 1420 was never true
1421 ref = id_to_ref[ref_id]
1422 for uri, storedFileInfo in zip(uris, infos):
1423 check_ref = ref
1424 if not ref.datasetType.isComponent() and (component := storedFileInfo.component):
1425 check_ref = ref.makeComponentRef(component)
1426 if self.cacheManager.known_to_cache(check_ref, uri.getExtension()):
1427 # Proxy for URI existence.
1428 uri_existence[uri] = True
1429 else:
1430 uris_to_check.append(uri)
1431 else:
1432 # Check all of them.
1433 uris_to_check.extend(uris)
1435 if artifact_existence is not None:
1436 # If a URI has already been checked remove it from the list
1437 # and immediately add the status to the output dict.
1438 filtered_uris_to_check = []
1439 for uri in uris_to_check:
1440 if uri in artifact_existence:
1441 uri_existence[uri] = artifact_existence[uri]
1442 else:
1443 filtered_uris_to_check.append(uri)
1444 uris_to_check = filtered_uris_to_check
1446 # Results.
1447 dataset_existence: Dict[DatasetRef, bool] = {}
1449 uri_existence.update(ResourcePath.mexists(uris_to_check))
1450 for uri, exists in uri_existence.items():
1451 dataset_id = location_map[uri]
1452 ref = id_to_ref[dataset_id]
1454 # Disassembled composite needs to check all locations.
1455 # all_required indicates whether all need to exist or not.
1456 if ref in dataset_existence:
1457 if all_required:
1458 exists = dataset_existence[ref] and exists
1459 else:
1460 exists = dataset_existence[ref] or exists
1461 dataset_existence[ref] = exists
1463 if artifact_existence is not None:
1464 artifact_existence.update(uri_existence)
1466 return dataset_existence
1468 def mexists(
1469 self, refs: Iterable[DatasetRef], artifact_existence: Optional[Dict[ResourcePath, bool]] = None
1470 ) -> Dict[DatasetRef, bool]:
1471 """Check the existence of multiple datasets at once.
1473 Parameters
1474 ----------
1475 refs : iterable of `DatasetRef`
1476 The datasets to be checked.
1477 artifact_existence : `dict` [`lsst.resources.ResourcePath`, `bool`]
1478 Optional mapping of datastore artifact to existence. Updated by
1479 this method with details of all artifacts tested. Can be `None`
1480 if the caller is not interested.
1482 Returns
1483 -------
1484 existence : `dict` of [`DatasetRef`, `bool`]
1485 Mapping from dataset to boolean indicating existence.
1487 Notes
1488 -----
1489 To minimize potentially costly remote existence checks, the local
1490 cache is checked as a proxy for existence. If a file for this
1491 `DatasetRef` does exist no check is done for the actual URI. This
1492 could result in possibly unexpected behavior if the dataset itself
1493 has been removed from the datastore by another process whilst it is
1494 still in the cache.
1495 """
1496 chunk_size = 10_000
1497 dataset_existence: Dict[DatasetRef, bool] = {}
1498 log.debug("Checking for the existence of multiple artifacts in datastore in chunks of %d", chunk_size)
1499 n_found_total = 0
1500 n_checked = 0
1501 n_chunks = 0
1502 for chunk in chunk_iterable(refs, chunk_size=chunk_size):
1503 chunk_result = self._mexists(chunk, artifact_existence)
1504 if log.isEnabledFor(VERBOSE):
1505 n_results = len(chunk_result)
1506 n_checked += n_results
1507 # Can treat the booleans as 0, 1 integers and sum them.
1508 n_found = sum(chunk_result.values())
1509 n_found_total += n_found
1510 log.verbose(
1511 "Number of datasets found in datastore for chunk %d = %d/%d (running total: %d/%d)",
1512 n_chunks,
1513 n_found,
1514 n_results,
1515 n_found_total,
1516 n_checked,
1517 )
1518 dataset_existence.update(chunk_result)
1519 n_chunks += 1
1521 return dataset_existence
1523 def _mexists(
1524 self, refs: Iterable[DatasetRef], artifact_existence: Optional[Dict[ResourcePath, bool]] = None
1525 ) -> Dict[DatasetRef, bool]:
1526 """Check the existence of multiple datasets at once.
1528 Parameters
1529 ----------
1530 refs : iterable of `DatasetRef`
1531 The datasets to be checked.
1533 Returns
1534 -------
1535 existence : `dict` of [`DatasetRef`, `bool`]
1536 Mapping from dataset to boolean indicating existence.
1537 """
1538 # Need a mapping of dataset_id to dataset ref since the API
1539 # works with dataset_id
1540 id_to_ref = {ref.getCheckedId(): ref for ref in refs}
1542 # Set of all IDs we are checking for.
1543 requested_ids = set(id_to_ref.keys())
1545 # The records themselves. Could be missing some entries.
1546 records = self._get_stored_records_associated_with_refs(refs)
1548 dataset_existence = self._process_mexists_records(
1549 id_to_ref, records, True, artifact_existence=artifact_existence
1550 )
1552 # Set of IDs that have been handled.
1553 handled_ids = {ref.id for ref in dataset_existence.keys()}
1555 missing_ids = requested_ids - handled_ids
1556 if missing_ids:
1557 if not self.trustGetRequest:
1558 # Must assume these do not exist
1559 for missing in missing_ids:
1560 dataset_existence[id_to_ref[missing]] = False
1561 else:
1562 log.debug(
1563 "%d out of %d datasets were not known to datastore during initial existence check.",
1564 len(missing_ids),
1565 len(requested_ids),
1566 )
1568 # Construct data structure identical to that returned
1569 # by _get_stored_records_associated_with_refs() but using
1570 # guessed names.
1571 records = {}
1572 for missing in missing_ids:
1573 expected = self._get_expected_dataset_locations_info(id_to_ref[missing])
1574 records[missing] = [info for _, info in expected]
1576 dataset_existence.update(
1577 self._process_mexists_records(
1578 id_to_ref, records, False, artifact_existence=artifact_existence
1579 )
1580 )
1582 return dataset_existence
1584 def exists(self, ref: DatasetRef) -> bool:
1585 """Check if the dataset exists in the datastore.
1587 Parameters
1588 ----------
1589 ref : `DatasetRef`
1590 Reference to the required dataset.
1592 Returns
1593 -------
1594 exists : `bool`
1595 `True` if the entity exists in the `Datastore`.
1597 Notes
1598 -----
1599 The local cache is checked as a proxy for existence in the remote
1600 object store. It is possible that another process on a different
1601 compute node could remove the file from the object store even
1602 though it is present in the local cache.
1603 """
1604 fileLocations = self._get_dataset_locations_info(ref)
1606 # if we are being asked to trust that registry might not be correct
1607 # we ask for the expected locations and check them explicitly
1608 if not fileLocations:
1609 if not self.trustGetRequest:
1610 return False
1612 # First check the cache. If it is not found we must check
1613 # the datastore itself. Assume that any component in the cache
1614 # means that the dataset does exist somewhere.
1615 if self.cacheManager.known_to_cache(ref): 1615 ↛ 1616line 1615 didn't jump to line 1616, because the condition on line 1615 was never true
1616 return True
1618 # When we are guessing a dataset location we can not check
1619 # for the existence of every component since we can not
1620 # know if every component was written. Instead we check
1621 # for the existence of any of the expected locations.
1622 for location, _ in self._get_expected_dataset_locations_info(ref):
1623 if self._artifact_exists(location):
1624 return True
1625 return False
1627 # All listed artifacts must exist.
1628 for location, storedFileInfo in fileLocations:
1629 # Checking in cache needs the component ref.
1630 check_ref = ref
1631 if not ref.datasetType.isComponent() and (component := storedFileInfo.component):
1632 check_ref = ref.makeComponentRef(component)
1633 if self.cacheManager.known_to_cache(check_ref, location.getExtension()):
1634 continue
1636 if not self._artifact_exists(location):
1637 return False
1639 return True
1641 def getURIs(self, ref: DatasetRef, predict: bool = False) -> DatasetRefURIs:
1642 """Return URIs associated with dataset.
1644 Parameters
1645 ----------
1646 ref : `DatasetRef`
1647 Reference to the required dataset.
1648 predict : `bool`, optional
1649 If the datastore does not know about the dataset, should it
1650 return a predicted URI or not?
1652 Returns
1653 -------
1654 uris : `DatasetRefURIs`
1655 The URI to the primary artifact associated with this dataset (if
1656 the dataset was disassembled within the datastore this may be
1657 `None`), and the URIs to any components associated with the dataset
1658 artifact. (can be empty if there are no components).
1659 """
1660 # if this has never been written then we have to guess
1661 if not self.exists(ref):
1662 if not predict:
1663 raise FileNotFoundError("Dataset {} not in this datastore".format(ref))
1665 return self._predict_URIs(ref)
1667 # If this is a ref that we have written we can get the path.
1668 # Get file metadata and internal metadata
1669 fileLocations = self._get_dataset_locations_info(ref)
1671 return self._locations_to_URI(ref, fileLocations)
1673 def getURI(self, ref: DatasetRef, predict: bool = False) -> ResourcePath:
1674 """URI to the Dataset.
1676 Parameters
1677 ----------
1678 ref : `DatasetRef`
1679 Reference to the required Dataset.
1680 predict : `bool`
1681 If `True`, allow URIs to be returned of datasets that have not
1682 been written.
1684 Returns
1685 -------
1686 uri : `str`
1687 URI pointing to the dataset within the datastore. If the
1688 dataset does not exist in the datastore, and if ``predict`` is
1689 `True`, the URI will be a prediction and will include a URI
1690 fragment "#predicted".
1691 If the datastore does not have entities that relate well
1692 to the concept of a URI the returned URI will be
1693 descriptive. The returned URI is not guaranteed to be obtainable.
1695 Raises
1696 ------
1697 FileNotFoundError
1698 Raised if a URI has been requested for a dataset that does not
1699 exist and guessing is not allowed.
1700 RuntimeError
1701 Raised if a request is made for a single URI but multiple URIs
1702 are associated with this dataset.
1704 Notes
1705 -----
1706 When a predicted URI is requested an attempt will be made to form
1707 a reasonable URI based on file templates and the expected formatter.
1708 """
1709 primary, components = self.getURIs(ref, predict)
1710 if primary is None or components: 1710 ↛ 1711line 1710 didn't jump to line 1711, because the condition on line 1710 was never true
1711 raise RuntimeError(
1712 f"Dataset ({ref}) includes distinct URIs for components. Use Datastore.getURIs() instead."
1713 )
1714 return primary
1716 def _predict_URIs(
1717 self,
1718 ref: DatasetRef,
1719 ) -> DatasetRefURIs:
1720 """Predict the URIs of a dataset ref.
1722 Parameters
1723 ----------
1724 ref : `DatasetRef`
1725 Reference to the required Dataset.
1727 Returns
1728 -------
1729 URI : DatasetRefUris
1730 Primary and component URIs. URIs will contain a URI fragment
1731 "#predicted".
1732 """
1733 uris = DatasetRefURIs()
1735 if self.composites.shouldBeDisassembled(ref):
1737 for component, _ in ref.datasetType.storageClass.components.items():
1738 comp_ref = ref.makeComponentRef(component)
1739 comp_location, _ = self._determine_put_formatter_location(comp_ref)
1741 # Add the "#predicted" URI fragment to indicate this is a
1742 # guess
1743 uris.componentURIs[component] = ResourcePath(comp_location.uri.geturl() + "#predicted")
1745 else:
1747 location, _ = self._determine_put_formatter_location(ref)
1749 # Add the "#predicted" URI fragment to indicate this is a guess
1750 uris.primaryURI = ResourcePath(location.uri.geturl() + "#predicted")
1752 return uris
1754 def getManyURIs(
1755 self,
1756 refs: Iterable[DatasetRef],
1757 predict: bool = False,
1758 allow_missing: bool = False,
1759 ) -> Dict[DatasetRef, DatasetRefURIs]:
1760 # Docstring inherited
1762 uris: Dict[DatasetRef, DatasetRefURIs] = {}
1764 records = self._get_stored_records_associated_with_refs(refs)
1765 records_keys = records.keys()
1767 existing_refs = (ref for ref in refs if ref.id in records_keys)
1768 missing_refs = (ref for ref in refs if ref.id not in records_keys)
1770 for ref in missing_refs:
1772 # if this has never been written then we have to guess
1773 if not predict:
1774 if not allow_missing:
1775 raise FileNotFoundError("Dataset {} not in this datastore.".format(ref))
1776 else:
1777 uris[ref] = self._predict_URIs(ref)
1779 for ref in existing_refs:
1780 file_infos = records[ref.getCheckedId()]
1781 file_locations = [(i.file_location(self.locationFactory), i) for i in file_infos]
1782 uris[ref] = self._locations_to_URI(ref, file_locations)
1784 return uris
1786 def _locations_to_URI(
1787 self,
1788 ref: DatasetRef,
1789 file_locations: Sequence[Tuple[Location, StoredFileInfo]],
1790 ) -> DatasetRefURIs:
1791 """Convert one or more file locations associated with a DatasetRef
1792 to a DatasetRefURIs.
1794 Parameters
1795 ----------
1796 ref : `DatasetRef`
1797 Reference to the dataset.
1798 file_locations : Sequence[Tuple[Location, StoredFileInfo]]
1799 Each item in the sequence is the location of the dataset within the
1800 datastore and stored information about the file and its formatter.
1801 If there is only one item in the sequence then it is treated as the
1802 primary URI. If there is more than one item then they are treated
1803 as component URIs. If there are no items then an error is raised
1804 unless ``self.trustGetRequest`` is `True`.
1806 Returns
1807 -------
1808 uris: DatasetRefURIs
1809 Represents the primary URI or component URIs described by the
1810 inputs.
1812 Raises
1813 ------
1814 RuntimeError
1815 If no file locations are passed in and ``self.trustGetRequest`` is
1816 `False`.
1817 FileNotFoundError
1818 If the a passed-in URI does not exist, and ``self.trustGetRequest``
1819 is `False`.
1820 RuntimeError
1821 If a passed in `StoredFileInfo`'s ``component`` is `None` (this is
1822 unexpected).
1823 """
1825 guessing = False
1826 uris = DatasetRefURIs()
1828 if not file_locations:
1829 if not self.trustGetRequest: 1829 ↛ 1830line 1829 didn't jump to line 1830, because the condition on line 1829 was never true
1830 raise RuntimeError(f"Unexpectedly got no artifacts for dataset {ref}")
1831 file_locations = self._get_expected_dataset_locations_info(ref)
1832 guessing = True
1834 if len(file_locations) == 1:
1835 # No disassembly so this is the primary URI
1836 uris.primaryURI = file_locations[0][0].uri
1837 if guessing and not uris.primaryURI.exists(): 1837 ↛ 1838line 1837 didn't jump to line 1838, because the condition on line 1837 was never true
1838 raise FileNotFoundError(f"Expected URI ({uris.primaryURI}) does not exist")
1839 else:
1840 for location, file_info in file_locations:
1841 if file_info.component is None: 1841 ↛ 1842line 1841 didn't jump to line 1842, because the condition on line 1841 was never true
1842 raise RuntimeError(f"Unexpectedly got no component name for a component at {location}")
1843 if guessing and not location.uri.exists(): 1843 ↛ 1847line 1843 didn't jump to line 1847, because the condition on line 1843 was never true
1844 # If we are trusting then it is entirely possible for
1845 # some components to be missing. In that case we skip
1846 # to the next component.
1847 if self.trustGetRequest:
1848 continue
1849 raise FileNotFoundError(f"Expected URI ({location.uri}) does not exist")
1850 uris.componentURIs[file_info.component] = location.uri
1852 return uris
1854 def retrieveArtifacts(
1855 self,
1856 refs: Iterable[DatasetRef],
1857 destination: ResourcePath,
1858 transfer: str = "auto",
1859 preserve_path: bool = True,
1860 overwrite: bool = False,
1861 ) -> List[ResourcePath]:
1862 """Retrieve the file artifacts associated with the supplied refs.
1864 Parameters
1865 ----------
1866 refs : iterable of `DatasetRef`
1867 The datasets for which file artifacts are to be retrieved.
1868 A single ref can result in multiple files. The refs must
1869 be resolved.
1870 destination : `lsst.resources.ResourcePath`
1871 Location to write the file artifacts.
1872 transfer : `str`, optional
1873 Method to use to transfer the artifacts. Must be one of the options
1874 supported by `lsst.resources.ResourcePath.transfer_from()`.
1875 "move" is not allowed.
1876 preserve_path : `bool`, optional
1877 If `True` the full path of the file artifact within the datastore
1878 is preserved. If `False` the final file component of the path
1879 is used.
1880 overwrite : `bool`, optional
1881 If `True` allow transfers to overwrite existing files at the
1882 destination.
1884 Returns
1885 -------
1886 targets : `list` of `lsst.resources.ResourcePath`
1887 URIs of file artifacts in destination location. Order is not
1888 preserved.
1889 """
1890 if not destination.isdir(): 1890 ↛ 1891line 1890 didn't jump to line 1891, because the condition on line 1890 was never true
1891 raise ValueError(f"Destination location must refer to a directory. Given {destination}")
1893 if transfer == "move":
1894 raise ValueError("Can not move artifacts out of datastore. Use copy instead.")
1896 # Source -> Destination
1897 # This also helps filter out duplicate DatasetRef in the request
1898 # that will map to the same underlying file transfer.
1899 to_transfer: Dict[ResourcePath, ResourcePath] = {}
1901 for ref in refs:
1902 locations = self._get_dataset_locations_info(ref)
1903 for location, _ in locations:
1904 source_uri = location.uri
1905 target_path: ResourcePathExpression
1906 if preserve_path:
1907 target_path = location.pathInStore
1908 if target_path.isabs(): 1908 ↛ 1911line 1908 didn't jump to line 1911, because the condition on line 1908 was never true
1909 # This is an absolute path to an external file.
1910 # Use the full path.
1911 target_path = target_path.relativeToPathRoot
1912 else:
1913 target_path = source_uri.basename()
1914 target_uri = destination.join(target_path)
1915 to_transfer[source_uri] = target_uri
1917 # In theory can now parallelize the transfer
1918 log.debug("Number of artifacts to transfer to %s: %d", str(destination), len(to_transfer))
1919 for source_uri, target_uri in to_transfer.items():
1920 target_uri.transfer_from(source_uri, transfer=transfer, overwrite=overwrite)
1922 return list(to_transfer.values())
1924 def get(
1925 self,
1926 ref: DatasetRef,
1927 parameters: Optional[Mapping[str, Any]] = None,
1928 storageClass: Optional[Union[StorageClass, str]] = None,
1929 ) -> Any:
1930 """Load an InMemoryDataset from the store.
1932 Parameters
1933 ----------
1934 ref : `DatasetRef`
1935 Reference to the required Dataset.
1936 parameters : `dict`
1937 `StorageClass`-specific parameters that specify, for example,
1938 a slice of the dataset to be loaded.
1939 storageClass : `StorageClass` or `str`, optional
1940 The storage class to be used to override the Python type
1941 returned by this method. By default the returned type matches
1942 the dataset type definition for this dataset. Specifying a
1943 read `StorageClass` can force a different type to be returned.
1944 This type must be compatible with the original type.
1946 Returns
1947 -------
1948 inMemoryDataset : `object`
1949 Requested dataset or slice thereof as an InMemoryDataset.
1951 Raises
1952 ------
1953 FileNotFoundError
1954 Requested dataset can not be retrieved.
1955 TypeError
1956 Return value from formatter has unexpected type.
1957 ValueError
1958 Formatter failed to process the dataset.
1959 """
1960 # Supplied storage class for the component being read is either
1961 # from the ref itself or some an override if we want to force
1962 # type conversion.
1963 if storageClass is not None:
1964 ref = ref.overrideStorageClass(storageClass)
1965 refStorageClass = ref.datasetType.storageClass
1967 allGetInfo = self._prepare_for_get(ref, parameters)
1968 refComponent = ref.datasetType.component()
1970 # Create mapping from component name to related info
1971 allComponents = {i.component: i for i in allGetInfo}
1973 # By definition the dataset is disassembled if we have more
1974 # than one record for it.
1975 isDisassembled = len(allGetInfo) > 1
1977 # Look for the special case where we are disassembled but the
1978 # component is a derived component that was not written during
1979 # disassembly. For this scenario we need to check that the
1980 # component requested is listed as a derived component for the
1981 # composite storage class
1982 isDisassembledReadOnlyComponent = False
1983 if isDisassembled and refComponent:
1984 # The composite storage class should be accessible through
1985 # the component dataset type
1986 compositeStorageClass = ref.datasetType.parentStorageClass
1988 # In the unlikely scenario where the composite storage
1989 # class is not known, we can only assume that this is a
1990 # normal component. If that assumption is wrong then the
1991 # branch below that reads a persisted component will fail
1992 # so there is no need to complain here.
1993 if compositeStorageClass is not None: 1993 ↛ 1996line 1993 didn't jump to line 1996, because the condition on line 1993 was never false
1994 isDisassembledReadOnlyComponent = refComponent in compositeStorageClass.derivedComponents
1996 if isDisassembled and not refComponent:
1997 # This was a disassembled dataset spread over multiple files
1998 # and we need to put them all back together again.
1999 # Read into memory and then assemble
2001 # Check that the supplied parameters are suitable for the type read
2002 refStorageClass.validateParameters(parameters)
2004 # We want to keep track of all the parameters that were not used
2005 # by formatters. We assume that if any of the component formatters
2006 # use a parameter that we do not need to apply it again in the
2007 # assembler.
2008 usedParams = set()
2010 components: Dict[str, Any] = {}
2011 for getInfo in allGetInfo:
2012 # assemblerParams are parameters not understood by the
2013 # associated formatter.
2014 usedParams.update(set(getInfo.formatterParams))
2016 component = getInfo.component
2018 if component is None: 2018 ↛ 2019line 2018 didn't jump to line 2019, because the condition on line 2018 was never true
2019 raise RuntimeError(f"Internal error in datastore assembly of {ref}")
2021 # We do not want the formatter to think it's reading
2022 # a component though because it is really reading a
2023 # standalone dataset -- always tell reader it is not a
2024 # component.
2025 components[component] = self._read_artifact_into_memory(
2026 getInfo, ref.makeComponentRef(component), isComponent=False
2027 )
2029 inMemoryDataset = ref.datasetType.storageClass.delegate().assemble(components)
2031 # Any unused parameters will have to be passed to the assembler
2032 if parameters:
2033 unusedParams = {k: v for k, v in parameters.items() if k not in usedParams}
2034 else:
2035 unusedParams = {}
2037 # Process parameters
2038 return ref.datasetType.storageClass.delegate().handleParameters(
2039 inMemoryDataset, parameters=unusedParams
2040 )
2042 elif isDisassembledReadOnlyComponent:
2044 compositeStorageClass = ref.datasetType.parentStorageClass
2045 if compositeStorageClass is None: 2045 ↛ 2046line 2045 didn't jump to line 2046, because the condition on line 2045 was never true
2046 raise RuntimeError(
2047 f"Unable to retrieve derived component '{refComponent}' since"
2048 "no composite storage class is available."
2049 )
2051 if refComponent is None: 2051 ↛ 2053line 2051 didn't jump to line 2053, because the condition on line 2051 was never true
2052 # Mainly for mypy
2053 raise RuntimeError(f"Internal error in datastore {self.name}: component can not be None here")
2055 # Assume that every derived component can be calculated by
2056 # forwarding the request to a single read/write component.
2057 # Rather than guessing which rw component is the right one by
2058 # scanning each for a derived component of the same name,
2059 # we ask the storage class delegate directly which one is best to
2060 # use.
2061 compositeDelegate = compositeStorageClass.delegate()
2062 forwardedComponent = compositeDelegate.selectResponsibleComponent(
2063 refComponent, set(allComponents)
2064 )
2066 # Select the relevant component
2067 rwInfo = allComponents[forwardedComponent]
2069 # For now assume that read parameters are validated against
2070 # the real component and not the requested component
2071 forwardedStorageClass = rwInfo.formatter.fileDescriptor.readStorageClass
2072 forwardedStorageClass.validateParameters(parameters)
2074 # The reference to use for the caching must refer to the forwarded
2075 # component and not the derived component.
2076 cache_ref = ref.makeCompositeRef().makeComponentRef(forwardedComponent)
2078 # Unfortunately the FileDescriptor inside the formatter will have
2079 # the wrong write storage class so we need to create a new one
2080 # given the immutability constraint.
2081 writeStorageClass = rwInfo.info.storageClass
2083 # We may need to put some thought into parameters for read
2084 # components but for now forward them on as is
2085 readFormatter = type(rwInfo.formatter)(
2086 FileDescriptor(
2087 rwInfo.location,
2088 readStorageClass=refStorageClass,
2089 storageClass=writeStorageClass,
2090 parameters=parameters,
2091 ),
2092 ref.dataId,
2093 )
2095 # The assembler can not receive any parameter requests for a
2096 # derived component at this time since the assembler will
2097 # see the storage class of the derived component and those
2098 # parameters will have to be handled by the formatter on the
2099 # forwarded storage class.
2100 assemblerParams: Dict[str, Any] = {}
2102 # Need to created a new info that specifies the derived
2103 # component and associated storage class
2104 readInfo = DatastoreFileGetInformation(
2105 rwInfo.location,
2106 readFormatter,
2107 rwInfo.info,
2108 assemblerParams,
2109 {},
2110 refComponent,
2111 refStorageClass,
2112 )
2114 return self._read_artifact_into_memory(readInfo, ref, isComponent=True, cache_ref=cache_ref)
2116 else:
2117 # Single file request or component from that composite file
2118 for lookup in (refComponent, None): 2118 ↛ 2123line 2118 didn't jump to line 2123, because the loop on line 2118 didn't complete
2119 if lookup in allComponents: 2119 ↛ 2118line 2119 didn't jump to line 2118, because the condition on line 2119 was never false
2120 getInfo = allComponents[lookup]
2121 break
2122 else:
2123 raise FileNotFoundError(
2124 f"Component {refComponent} not found for ref {ref} in datastore {self.name}"
2125 )
2127 # Do not need the component itself if already disassembled
2128 if isDisassembled:
2129 isComponent = False
2130 else:
2131 isComponent = getInfo.component is not None
2133 # For a component read of a composite we want the cache to
2134 # be looking at the composite ref itself.
2135 cache_ref = ref.makeCompositeRef() if isComponent else ref
2137 # For a disassembled component we can validate parametersagainst
2138 # the component storage class directly
2139 if isDisassembled:
2140 refStorageClass.validateParameters(parameters)
2141 else:
2142 # For an assembled composite this could be a derived
2143 # component derived from a real component. The validity
2144 # of the parameters is not clear. For now validate against
2145 # the composite storage class
2146 getInfo.formatter.fileDescriptor.storageClass.validateParameters(parameters)
2148 return self._read_artifact_into_memory(getInfo, ref, isComponent=isComponent, cache_ref=cache_ref)
2150 @transactional
2151 def put(self, inMemoryDataset: Any, ref: DatasetRef) -> None:
2152 """Write a InMemoryDataset with a given `DatasetRef` to the store.
2154 Parameters
2155 ----------
2156 inMemoryDataset : `object`
2157 The dataset to store.
2158 ref : `DatasetRef`
2159 Reference to the associated Dataset.
2161 Raises
2162 ------
2163 TypeError
2164 Supplied object and storage class are inconsistent.
2165 DatasetTypeNotSupportedError
2166 The associated `DatasetType` is not handled by this datastore.
2168 Notes
2169 -----
2170 If the datastore is configured to reject certain dataset types it
2171 is possible that the put will fail and raise a
2172 `DatasetTypeNotSupportedError`. The main use case for this is to
2173 allow `ChainedDatastore` to put to multiple datastores without
2174 requiring that every datastore accepts the dataset.
2175 """
2177 doDisassembly = self.composites.shouldBeDisassembled(ref)
2178 # doDisassembly = True
2180 artifacts = []
2181 if doDisassembly:
2182 components = ref.datasetType.storageClass.delegate().disassemble(inMemoryDataset)
2183 if components is None: 2183 ↛ 2184line 2183 didn't jump to line 2184, because the condition on line 2183 was never true
2184 raise RuntimeError(
2185 f"Inconsistent configuration: dataset type {ref.datasetType.name} "
2186 f"with storage class {ref.datasetType.storageClass.name} "
2187 "is configured to be disassembled, but cannot be."
2188 )
2189 for component, componentInfo in components.items():
2190 # Don't recurse because we want to take advantage of
2191 # bulk insert -- need a new DatasetRef that refers to the
2192 # same dataset_id but has the component DatasetType
2193 # DatasetType does not refer to the types of components
2194 # So we construct one ourselves.
2195 compRef = ref.makeComponentRef(component)
2196 storedInfo = self._write_in_memory_to_artifact(componentInfo.component, compRef)
2197 artifacts.append((compRef, storedInfo))
2198 else:
2199 # Write the entire thing out
2200 storedInfo = self._write_in_memory_to_artifact(inMemoryDataset, ref)
2201 artifacts.append((ref, storedInfo))
2203 self._register_datasets(artifacts)
2205 @transactional
2206 def trash(self, ref: Union[DatasetRef, Iterable[DatasetRef]], ignore_errors: bool = True) -> None:
2207 # At this point can safely remove these datasets from the cache
2208 # to avoid confusion later on. If they are not trashed later
2209 # the cache will simply be refilled.
2210 self.cacheManager.remove_from_cache(ref)
2212 # If we are in trust mode there will be nothing to move to
2213 # the trash table and we will have to try to delete the file
2214 # immediately.
2215 if self.trustGetRequest:
2216 # Try to keep the logic below for a single file trash.
2217 if isinstance(ref, DatasetRef):
2218 refs = {ref}
2219 else:
2220 # Will recreate ref at the end of this branch.
2221 refs = set(ref)
2223 # Determine which datasets are known to datastore directly.
2224 id_to_ref = {ref.getCheckedId(): ref for ref in refs}
2225 existing_ids = self._get_stored_records_associated_with_refs(refs)
2226 existing_refs = {id_to_ref[ref_id] for ref_id in existing_ids}
2228 missing = refs - existing_refs
2229 if missing:
2230 # Do an explicit existence check on these refs.
2231 # We only care about the artifacts at this point and not
2232 # the dataset existence.
2233 artifact_existence: Dict[ResourcePath, bool] = {}
2234 _ = self.mexists(missing, artifact_existence)
2235 uris = [uri for uri, exists in artifact_existence.items() if exists]
2237 # FUTURE UPGRADE: Implement a parallelized bulk remove.
2238 log.debug("Removing %d artifacts from datastore that are unknown to datastore", len(uris))
2239 for uri in uris:
2240 try:
2241 uri.remove()
2242 except Exception as e:
2243 if ignore_errors:
2244 log.debug("Artifact %s could not be removed: %s", uri, e)
2245 continue
2246 raise
2248 # There is no point asking the code below to remove refs we
2249 # know are missing so update it with the list of existing
2250 # records. Try to retain one vs many logic.
2251 if not existing_refs:
2252 # Nothing more to do since none of the datasets were
2253 # known to the datastore record table.
2254 return
2255 ref = list(existing_refs)
2256 if len(ref) == 1:
2257 ref = ref[0]
2259 # Get file metadata and internal metadata
2260 if not isinstance(ref, DatasetRef):
2261 log.debug("Doing multi-dataset trash in datastore %s", self.name)
2262 # Assumed to be an iterable of refs so bulk mode enabled.
2263 try:
2264 self.bridge.moveToTrash(ref, transaction=self._transaction)
2265 except Exception as e:
2266 if ignore_errors:
2267 log.warning("Unexpected issue moving multiple datasets to trash: %s", e)
2268 else:
2269 raise
2270 return
2272 log.debug("Trashing dataset %s in datastore %s", ref, self.name)
2274 fileLocations = self._get_dataset_locations_info(ref)
2276 if not fileLocations:
2277 err_msg = f"Requested dataset to trash ({ref}) is not known to datastore {self.name}"
2278 if ignore_errors:
2279 log.warning(err_msg)
2280 return
2281 else:
2282 raise FileNotFoundError(err_msg)
2284 for location, storedFileInfo in fileLocations:
2285 if not self._artifact_exists(location): 2285 ↛ 2286line 2285 didn't jump to line 2286
2286 err_msg = (
2287 f"Dataset is known to datastore {self.name} but "
2288 f"associated artifact ({location.uri}) is missing"
2289 )
2290 if ignore_errors:
2291 log.warning(err_msg)
2292 return
2293 else:
2294 raise FileNotFoundError(err_msg)
2296 # Mark dataset as trashed
2297 try:
2298 self.bridge.moveToTrash([ref], transaction=self._transaction)
2299 except Exception as e:
2300 if ignore_errors:
2301 log.warning(
2302 "Attempted to mark dataset (%s) to be trashed in datastore %s "
2303 "but encountered an error: %s",
2304 ref,
2305 self.name,
2306 e,
2307 )
2308 pass
2309 else:
2310 raise
2312 @transactional
2313 def emptyTrash(self, ignore_errors: bool = True) -> None:
2314 """Remove all datasets from the trash.
2316 Parameters
2317 ----------
2318 ignore_errors : `bool`
2319 If `True` return without error even if something went wrong.
2320 Problems could occur if another process is simultaneously trying
2321 to delete.
2322 """
2323 log.debug("Emptying trash in datastore %s", self.name)
2325 # Context manager will empty trash iff we finish it without raising.
2326 # It will also automatically delete the relevant rows from the
2327 # trash table and the records table.
2328 with self.bridge.emptyTrash(
2329 self._table, record_class=StoredFileInfo, record_column="path"
2330 ) as trash_data:
2331 # Removing the artifacts themselves requires that the files are
2332 # not also associated with refs that are not to be trashed.
2333 # Therefore need to do a query with the file paths themselves
2334 # and return all the refs associated with them. Can only delete
2335 # a file if the refs to be trashed are the only refs associated
2336 # with the file.
2337 # This requires multiple copies of the trashed items
2338 trashed, artifacts_to_keep = trash_data
2340 if artifacts_to_keep is None:
2341 # The bridge is not helping us so have to work it out
2342 # ourselves. This is not going to be as efficient.
2343 trashed = list(trashed)
2345 # The instance check is for mypy since up to this point it
2346 # does not know the type of info.
2347 path_map = self._refs_associated_with_artifacts(
2348 [info.path for _, info in trashed if isinstance(info, StoredFileInfo)]
2349 )
2351 for ref, info in trashed:
2353 # Mypy needs to know this is not the base class
2354 assert isinstance(info, StoredFileInfo), f"Unexpectedly got info of class {type(info)}"
2356 # Check for mypy
2357 assert ref.id is not None, f"Internal logic error in emptyTrash with ref {ref}/{info}"
2359 path_map[info.path].remove(ref.id)
2360 if not path_map[info.path]: 2360 ↛ 2351line 2360 didn't jump to line 2351, because the condition on line 2360 was never false
2361 del path_map[info.path]
2363 artifacts_to_keep = set(path_map)
2365 for ref, info in trashed:
2367 # Should not happen for this implementation but need
2368 # to keep mypy happy.
2369 assert info is not None, f"Internal logic error in emptyTrash with ref {ref}."
2371 # Mypy needs to know this is not the base class
2372 assert isinstance(info, StoredFileInfo), f"Unexpectedly got info of class {type(info)}"
2374 # Check for mypy
2375 assert ref.id is not None, f"Internal logic error in emptyTrash with ref {ref}/{info}"
2377 if info.path in artifacts_to_keep:
2378 # This is a multi-dataset artifact and we are not
2379 # removing all associated refs.
2380 continue
2382 # Only trashed refs still known to datastore will be returned.
2383 location = info.file_location(self.locationFactory)
2385 # Point of no return for this artifact
2386 log.debug("Removing artifact %s from datastore %s", location.uri, self.name)
2387 try:
2388 self._delete_artifact(location)
2389 except FileNotFoundError:
2390 # If the file itself has been deleted there is nothing
2391 # we can do about it. It is possible that trash has
2392 # been run in parallel in another process or someone
2393 # decided to delete the file. It is unlikely to come
2394 # back and so we should still continue with the removal
2395 # of the entry from the trash table. It is also possible
2396 # we removed it in a previous iteration if it was
2397 # a multi-dataset artifact. The delete artifact method
2398 # will log a debug message in this scenario.
2399 # Distinguishing file missing before trash started and
2400 # file already removed previously as part of this trash
2401 # is not worth the distinction with regards to potential
2402 # memory cost.
2403 pass
2404 except Exception as e:
2405 if ignore_errors:
2406 # Use a debug message here even though it's not
2407 # a good situation. In some cases this can be
2408 # caused by a race between user A and user B
2409 # and neither of them has permissions for the
2410 # other's files. Butler does not know about users
2411 # and trash has no idea what collections these
2412 # files were in (without guessing from a path).
2413 log.debug(
2414 "Encountered error removing artifact %s from datastore %s: %s",
2415 location.uri,
2416 self.name,
2417 e,
2418 )
2419 else:
2420 raise
2422 @transactional
2423 def transfer_from(
2424 self,
2425 source_datastore: Datastore,
2426 refs: Iterable[DatasetRef],
2427 local_refs: Optional[Iterable[DatasetRef]] = None,
2428 transfer: str = "auto",
2429 artifact_existence: Optional[Dict[ResourcePath, bool]] = None,
2430 ) -> None:
2431 # Docstring inherited
2432 if type(self) is not type(source_datastore):
2433 raise TypeError(
2434 f"Datastore mismatch between this datastore ({type(self)}) and the "
2435 f"source datastore ({type(source_datastore)})."
2436 )
2438 # Be explicit for mypy
2439 if not isinstance(source_datastore, FileDatastore): 2439 ↛ 2440line 2439 didn't jump to line 2440, because the condition on line 2439 was never true
2440 raise TypeError(
2441 "Can only transfer to a FileDatastore from another FileDatastore, not"
2442 f" {type(source_datastore)}"
2443 )
2445 # Stop early if "direct" transfer mode is requested. That would
2446 # require that the URI inside the source datastore should be stored
2447 # directly in the target datastore, which seems unlikely to be useful
2448 # since at any moment the source datastore could delete the file.
2449 if transfer in ("direct", "split"):
2450 raise ValueError(
2451 f"Can not transfer from a source datastore using {transfer} mode since"
2452 " those files are controlled by the other datastore."
2453 )
2455 # Empty existence lookup if none given.
2456 if artifact_existence is None:
2457 artifact_existence = {}
2459 # We will go through the list multiple times so must convert
2460 # generators to lists.
2461 refs = list(refs)
2463 if local_refs is None:
2464 local_refs = refs
2465 else:
2466 local_refs = list(local_refs)
2468 # In order to handle disassembled composites the code works
2469 # at the records level since it can assume that internal APIs
2470 # can be used.
2471 # - If the record already exists in the destination this is assumed
2472 # to be okay.
2473 # - If there is no record but the source and destination URIs are
2474 # identical no transfer is done but the record is added.
2475 # - If the source record refers to an absolute URI currently assume
2476 # that that URI should remain absolute and will be visible to the
2477 # destination butler. May need to have a flag to indicate whether
2478 # the dataset should be transferred. This will only happen if
2479 # the detached Butler has had a local ingest.
2481 # What we really want is all the records in the source datastore
2482 # associated with these refs. Or derived ones if they don't exist
2483 # in the source.
2484 source_records = source_datastore._get_stored_records_associated_with_refs(refs)
2486 # The source dataset_ids are the keys in these records
2487 source_ids = set(source_records)
2488 log.debug("Number of datastore records found in source: %d", len(source_ids))
2490 # The not None check is to appease mypy
2491 requested_ids = set(ref.id for ref in refs if ref.id is not None)
2492 missing_ids = requested_ids - source_ids
2494 # Missing IDs can be okay if that datastore has allowed
2495 # gets based on file existence. Should we transfer what we can
2496 # or complain about it and warn?
2497 if missing_ids and not source_datastore.trustGetRequest: 2497 ↛ 2498line 2497 didn't jump to line 2498, because the condition on line 2497 was never true
2498 raise ValueError(
2499 f"Some datasets are missing from source datastore {source_datastore}: {missing_ids}"
2500 )
2502 # Need to map these missing IDs to a DatasetRef so we can guess
2503 # the details.
2504 if missing_ids:
2505 log.info(
2506 "Number of expected datasets missing from source datastore records: %d out of %d",
2507 len(missing_ids),
2508 len(requested_ids),
2509 )
2510 id_to_ref = {ref.id: ref for ref in refs if ref.id in missing_ids}
2512 # This should be chunked in case we end up having to check
2513 # the file store since we need some log output to show
2514 # progress.
2515 for missing_ids_chunk in chunk_iterable(missing_ids, chunk_size=10_000):
2516 records = {}
2517 for missing in missing_ids_chunk:
2518 # Ask the source datastore where the missing artifacts
2519 # should be. An execution butler might not know about the
2520 # artifacts even if they are there.
2521 expected = source_datastore._get_expected_dataset_locations_info(id_to_ref[missing])
2522 records[missing] = [info for _, info in expected]
2524 # Call the mexist helper method in case we have not already
2525 # checked these artifacts such that artifact_existence is
2526 # empty. This allows us to benefit from parallelism.
2527 # datastore.mexists() itself does not give us access to the
2528 # derived datastore record.
2529 log.verbose("Checking existence of %d datasets unknown to datastore", len(records))
2530 ref_exists = source_datastore._process_mexists_records(
2531 id_to_ref, records, False, artifact_existence=artifact_existence
2532 )
2534 # Now go through the records and propagate the ones that exist.
2535 location_factory = source_datastore.locationFactory
2536 for missing, record_list in records.items():
2537 # Skip completely if the ref does not exist.
2538 ref = id_to_ref[missing]
2539 if not ref_exists[ref]:
2540 log.warning("Asked to transfer dataset %s but no file artifacts exist for it.", ref)
2541 continue
2542 # Check for file artifact to decide which parts of a
2543 # disassembled composite do exist. If there is only a
2544 # single record we don't even need to look because it can't
2545 # be a composite and must exist.
2546 if len(record_list) == 1:
2547 dataset_records = record_list
2548 else:
2549 dataset_records = [
2550 record
2551 for record in record_list
2552 if artifact_existence[record.file_location(location_factory).uri]
2553 ]
2554 assert len(dataset_records) > 0, "Disassembled composite should have had some files."
2556 # Rely on source_records being a defaultdict.
2557 source_records[missing].extend(dataset_records)
2559 # See if we already have these records
2560 target_records = self._get_stored_records_associated_with_refs(local_refs)
2562 # The artifacts to register
2563 artifacts = []
2565 # Refs that already exist
2566 already_present = []
2568 # Now can transfer the artifacts
2569 for source_ref, target_ref in zip(refs, local_refs):
2570 if target_ref.id in target_records:
2571 # Already have an artifact for this.
2572 already_present.append(target_ref)
2573 continue
2575 # mypy needs to know these are always resolved refs
2576 for info in source_records[source_ref.getCheckedId()]:
2577 source_location = info.file_location(source_datastore.locationFactory)
2578 target_location = info.file_location(self.locationFactory)
2579 if source_location == target_location: 2579 ↛ 2583line 2579 didn't jump to line 2583, because the condition on line 2579 was never true
2580 # Either the dataset is already in the target datastore
2581 # (which is how execution butler currently runs) or
2582 # it is an absolute URI.
2583 if source_location.pathInStore.isabs():
2584 # Just because we can see the artifact when running
2585 # the transfer doesn't mean it will be generally
2586 # accessible to a user of this butler. For now warn
2587 # but assume it will be accessible.
2588 log.warning(
2589 "Transfer request for an outside-datastore artifact has been found at %s",
2590 source_location,
2591 )
2592 else:
2593 # Need to transfer it to the new location.
2594 # Assume we should always overwrite. If the artifact
2595 # is there this might indicate that a previous transfer
2596 # was interrupted but was not able to be rolled back
2597 # completely (eg pre-emption) so follow Datastore default
2598 # and overwrite.
2599 target_location.uri.transfer_from(
2600 source_location.uri, transfer=transfer, overwrite=True, transaction=self._transaction
2601 )
2603 artifacts.append((target_ref, info))
2605 self._register_datasets(artifacts)
2607 if already_present:
2608 n_skipped = len(already_present)
2609 log.info(
2610 "Skipped transfer of %d dataset%s already present in datastore",
2611 n_skipped,
2612 "" if n_skipped == 1 else "s",
2613 )
2615 @transactional
2616 def forget(self, refs: Iterable[DatasetRef]) -> None:
2617 # Docstring inherited.
2618 refs = list(refs)
2619 self.bridge.forget(refs)
2620 self._table.delete(["dataset_id"], *[{"dataset_id": ref.getCheckedId()} for ref in refs])
2622 def validateConfiguration(
2623 self, entities: Iterable[Union[DatasetRef, DatasetType, StorageClass]], logFailures: bool = False
2624 ) -> None:
2625 """Validate some of the configuration for this datastore.
2627 Parameters
2628 ----------
2629 entities : iterable of `DatasetRef`, `DatasetType`, or `StorageClass`
2630 Entities to test against this configuration. Can be differing
2631 types.
2632 logFailures : `bool`, optional
2633 If `True`, output a log message for every validation error
2634 detected.
2636 Raises
2637 ------
2638 DatastoreValidationError
2639 Raised if there is a validation problem with a configuration.
2640 All the problems are reported in a single exception.
2642 Notes
2643 -----
2644 This method checks that all the supplied entities have valid file
2645 templates and also have formatters defined.
2646 """
2648 templateFailed = None
2649 try:
2650 self.templates.validateTemplates(entities, logFailures=logFailures)
2651 except FileTemplateValidationError as e:
2652 templateFailed = str(e)
2654 formatterFailed = []
2655 for entity in entities:
2656 try:
2657 self.formatterFactory.getFormatterClass(entity)
2658 except KeyError as e:
2659 formatterFailed.append(str(e))
2660 if logFailures: 2660 ↛ 2655line 2660 didn't jump to line 2655, because the condition on line 2660 was never false
2661 log.critical("Formatter failure: %s", e)
2663 if templateFailed or formatterFailed:
2664 messages = []
2665 if templateFailed: 2665 ↛ 2666line 2665 didn't jump to line 2666, because the condition on line 2665 was never true
2666 messages.append(templateFailed)
2667 if formatterFailed: 2667 ↛ 2669line 2667 didn't jump to line 2669, because the condition on line 2667 was never false
2668 messages.append(",".join(formatterFailed))
2669 msg = ";\n".join(messages)
2670 raise DatastoreValidationError(msg)
2672 def getLookupKeys(self) -> Set[LookupKey]:
2673 # Docstring is inherited from base class
2674 return (
2675 self.templates.getLookupKeys()
2676 | self.formatterFactory.getLookupKeys()
2677 | self.constraints.getLookupKeys()
2678 )
2680 def validateKey(self, lookupKey: LookupKey, entity: Union[DatasetRef, DatasetType, StorageClass]) -> None:
2681 # Docstring is inherited from base class
2682 # The key can be valid in either formatters or templates so we can
2683 # only check the template if it exists
2684 if lookupKey in self.templates:
2685 try:
2686 self.templates[lookupKey].validateTemplate(entity)
2687 except FileTemplateValidationError as e:
2688 raise DatastoreValidationError(e) from e
2690 def export(
2691 self,
2692 refs: Iterable[DatasetRef],
2693 *,
2694 directory: Optional[ResourcePathExpression] = None,
2695 transfer: Optional[str] = "auto",
2696 ) -> Iterable[FileDataset]:
2697 # Docstring inherited from Datastore.export.
2698 if transfer is not None and directory is None: 2698 ↛ 2699line 2698 didn't jump to line 2699, because the condition on line 2698 was never true
2699 raise RuntimeError(f"Cannot export using transfer mode {transfer} with no export directory given")
2701 if transfer == "move": 2701 ↛ 2702line 2701 didn't jump to line 2702, because the condition on line 2701 was never true
2702 raise RuntimeError("Can not export by moving files out of datastore.")
2703 elif transfer == "direct": 2703 ↛ 2707line 2703 didn't jump to line 2707, because the condition on line 2703 was never true
2704 # For an export, treat this as equivalent to None. We do not
2705 # want an import to risk using absolute URIs to datasets owned
2706 # by another datastore.
2707 log.info("Treating 'direct' transfer mode as in-place export.")
2708 transfer = None
2710 # Force the directory to be a URI object
2711 directoryUri: Optional[ResourcePath] = None
2712 if directory is not None: 2712 ↛ 2715line 2712 didn't jump to line 2715, because the condition on line 2712 was never false
2713 directoryUri = ResourcePath(directory, forceDirectory=True)
2715 if transfer is not None and directoryUri is not None: 2715 ↛ 2720line 2715 didn't jump to line 2720, because the condition on line 2715 was never false
2716 # mypy needs the second test
2717 if not directoryUri.exists(): 2717 ↛ 2718line 2717 didn't jump to line 2718, because the condition on line 2717 was never true
2718 raise FileNotFoundError(f"Export location {directory} does not exist")
2720 progress = Progress("lsst.daf.butler.datastores.FileDatastore.export", level=logging.DEBUG)
2721 for ref in progress.wrap(refs, "Exporting dataset files"):
2722 fileLocations = self._get_dataset_locations_info(ref)
2723 if not fileLocations: 2723 ↛ 2724line 2723 didn't jump to line 2724, because the condition on line 2723 was never true
2724 raise FileNotFoundError(f"Could not retrieve dataset {ref}.")
2725 # For now we can not export disassembled datasets
2726 if len(fileLocations) > 1:
2727 raise NotImplementedError(f"Can not export disassembled datasets such as {ref}")
2728 location, storedFileInfo = fileLocations[0]
2730 pathInStore = location.pathInStore.path
2731 if transfer is None: 2731 ↛ 2735line 2731 didn't jump to line 2735, because the condition on line 2731 was never true
2732 # TODO: do we also need to return the readStorageClass somehow?
2733 # We will use the path in store directly. If this is an
2734 # absolute URI, preserve it.
2735 if location.pathInStore.isabs():
2736 pathInStore = str(location.uri)
2737 elif transfer == "direct": 2737 ↛ 2739line 2737 didn't jump to line 2739, because the condition on line 2737 was never true
2738 # Use full URIs to the remote store in the export
2739 pathInStore = str(location.uri)
2740 else:
2741 # mypy needs help
2742 assert directoryUri is not None, "directoryUri must be defined to get here"
2743 storeUri = ResourcePath(location.uri)
2745 # if the datastore has an absolute URI to a resource, we
2746 # have two options:
2747 # 1. Keep the absolute URI in the exported YAML
2748 # 2. Allocate a new name in the local datastore and transfer
2749 # it.
2750 # For now go with option 2
2751 if location.pathInStore.isabs(): 2751 ↛ 2752line 2751 didn't jump to line 2752, because the condition on line 2751 was never true
2752 template = self.templates.getTemplate(ref)
2753 newURI = ResourcePath(template.format(ref), forceAbsolute=False)
2754 pathInStore = str(newURI.updatedExtension(location.pathInStore.getExtension()))
2756 exportUri = directoryUri.join(pathInStore)
2757 exportUri.transfer_from(storeUri, transfer=transfer)
2759 yield FileDataset(refs=[ref], path=pathInStore, formatter=storedFileInfo.formatter)
2761 @staticmethod
2762 def computeChecksum(
2763 uri: ResourcePath, algorithm: str = "blake2b", block_size: int = 8192
2764 ) -> Optional[str]:
2765 """Compute the checksum of the supplied file.
2767 Parameters
2768 ----------
2769 uri : `lsst.resources.ResourcePath`
2770 Name of resource to calculate checksum from.
2771 algorithm : `str`, optional
2772 Name of algorithm to use. Must be one of the algorithms supported
2773 by :py:class`hashlib`.
2774 block_size : `int`
2775 Number of bytes to read from file at one time.
2777 Returns
2778 -------
2779 hexdigest : `str`
2780 Hex digest of the file.
2782 Notes
2783 -----
2784 Currently returns None if the URI is for a remote resource.
2785 """
2786 if algorithm not in hashlib.algorithms_guaranteed: 2786 ↛ 2787line 2786 didn't jump to line 2787, because the condition on line 2786 was never true
2787 raise NameError("The specified algorithm '{}' is not supported by hashlib".format(algorithm))
2789 if not uri.isLocal: 2789 ↛ 2790line 2789 didn't jump to line 2790, because the condition on line 2789 was never true
2790 return None
2792 hasher = hashlib.new(algorithm)
2794 with uri.as_local() as local_uri:
2795 with open(local_uri.ospath, "rb") as f:
2796 for chunk in iter(lambda: f.read(block_size), b""):
2797 hasher.update(chunk)
2799 return hasher.hexdigest()
2801 def needs_expanded_data_ids(
2802 self,
2803 transfer: Optional[str],
2804 entity: Optional[Union[DatasetRef, DatasetType, StorageClass]] = None,
2805 ) -> bool:
2806 # Docstring inherited.
2807 # This _could_ also use entity to inspect whether the filename template
2808 # involves placeholders other than the required dimensions for its
2809 # dataset type, but that's not necessary for correctness; it just
2810 # enables more optimizations (perhaps only in theory).
2811 return transfer not in ("direct", None)
2813 def import_records(self, data: Mapping[str, DatastoreRecordData]) -> None:
2814 # Docstring inherited from the base class.
2815 record_data = data.get(self.name)
2816 if not record_data: 2816 ↛ 2817line 2816 didn't jump to line 2817, because the condition on line 2816 was never true
2817 return
2819 self._bridge.insert(FakeDatasetRef(dataset_id) for dataset_id in record_data.records.keys())
2821 # TODO: Verify that there are no unexpected table names in the dict?
2822 unpacked_records = []
2823 for dataset_data in record_data.records.values():
2824 records = dataset_data.get(self._table.name)
2825 if records: 2825 ↛ 2823line 2825 didn't jump to line 2823, because the condition on line 2825 was never false
2826 for info in records:
2827 assert isinstance(info, StoredFileInfo), "Expecting StoredFileInfo records"
2828 unpacked_records.append(info.to_record())
2829 if unpacked_records:
2830 self._table.insert(*unpacked_records)
2832 def export_records(self, refs: Iterable[DatasetIdRef]) -> Mapping[str, DatastoreRecordData]:
2833 # Docstring inherited from the base class.
2834 exported_refs = list(self._bridge.check(refs))
2835 ids = {ref.getCheckedId() for ref in exported_refs}
2836 records: defaultdict[DatasetId, defaultdict[str, List[StoredDatastoreItemInfo]]] = defaultdict(
2837 lambda: defaultdict(list), {id: defaultdict(list) for id in ids}
2838 )
2839 for row in self._table.fetch(dataset_id=ids):
2840 info: StoredDatastoreItemInfo = StoredFileInfo.from_record(row)
2841 records[info.dataset_id][self._table.name].append(info)
2843 record_data = DatastoreRecordData(records=records)
2844 return {self.name: record_data}