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