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