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