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