Coverage for python/lsst/daf/butler/transfers/_yaml.py: 12%
169 statements
« prev ^ index » next coverage.py v6.5.0, created at 2022-12-01 19:55 +0000
« prev ^ index » next coverage.py v6.5.0, created at 2022-12-01 19:55 +0000
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22from __future__ import annotations
24__all__ = ["YamlRepoExportBackend", "YamlRepoImportBackend"]
26from datetime import datetime
27from typing import (
28 Any,
29 Dict,
30 IO,
31 Iterable,
32 List,
33 Mapping,
34 Optional,
35 Set,
36 Tuple,
37 Type,
38)
39import uuid
40import warnings
41from collections import defaultdict
43import yaml
44import astropy.time
46from lsst.utils import doImport
47from ..core import (
48 DatasetAssociation,
49 DatasetId,
50 DatasetRef,
51 DatasetType,
52 Datastore,
53 DimensionElement,
54 DimensionRecord,
55 FileDataset,
56 Timespan,
57)
58from ..core._butlerUri import ButlerURI
59from ..core.utils import iterable
60from ..core.named import NamedValueSet
61from ..registry import CollectionType, Registry
62from ..registry.interfaces import (
63 ChainedCollectionRecord,
64 CollectionRecord,
65 DatasetIdGenEnum,
66 RunRecord,
67 VersionTuple,
68)
69from ..registry.versions import IncompatibleVersionError
70from ._interfaces import RepoExportBackend, RepoImportBackend
73EXPORT_FORMAT_VERSION = VersionTuple(1, 0, 1)
74"""Export format version.
76Files with a different major version or a newer minor version cannot be read by
77this version of the code.
78"""
81def _uuid_representer(dumper: yaml.Dumper, data: uuid.UUID) -> yaml.Node:
82 """Generate YAML representation for UUID.
84 This produces a scalar node with a tag "!uuid" and value being a regular
85 string representation of UUID.
86 """
87 return dumper.represent_scalar("!uuid", str(data))
90def _uuid_constructor(loader: yaml.Loader, node: yaml.Node) -> Optional[uuid.UUID]:
91 if node.value is not None:
92 return uuid.UUID(hex=node.value)
93 return None
96yaml.Dumper.add_representer(uuid.UUID, _uuid_representer)
97yaml.SafeLoader.add_constructor("!uuid", _uuid_constructor)
100class YamlRepoExportBackend(RepoExportBackend):
101 """A repository export implementation that saves to a YAML file.
103 Parameters
104 ----------
105 stream
106 A writeable file-like object.
107 """
109 def __init__(self, stream: IO):
110 self.stream = stream
111 self.data: List[Dict[str, Any]] = []
113 def saveDimensionData(self, element: DimensionElement, *data: DimensionRecord) -> None:
114 # Docstring inherited from RepoExportBackend.saveDimensionData.
115 data_dicts = [record.toDict(splitTimespan=True) for record in data]
116 self.data.append({
117 "type": "dimension",
118 "element": element.name,
119 "records": data_dicts,
120 })
122 def saveCollection(self, record: CollectionRecord, doc: Optional[str]) -> None:
123 # Docstring inherited from RepoExportBackend.saveCollections.
124 data: Dict[str, Any] = {
125 "type": "collection",
126 "collection_type": record.type.name,
127 "name": record.name,
128 }
129 if doc is not None:
130 data["doc"] = doc
131 if isinstance(record, RunRecord):
132 data["host"] = record.host
133 data["timespan_begin"] = record.timespan.begin
134 data["timespan_end"] = record.timespan.end
135 elif isinstance(record, ChainedCollectionRecord):
136 data["children"] = list(record.children)
137 self.data.append(data)
139 def saveDatasets(self, datasetType: DatasetType, run: str, *datasets: FileDataset) -> None:
140 # Docstring inherited from RepoExportBackend.saveDatasets.
141 self.data.append({
142 "type": "dataset_type",
143 "name": datasetType.name,
144 "dimensions": [d.name for d in datasetType.dimensions],
145 "storage_class": datasetType.storageClass.name,
146 "is_calibration": datasetType.isCalibration(),
147 })
148 self.data.append({
149 "type": "dataset",
150 "dataset_type": datasetType.name,
151 "run": run,
152 "records": [
153 {
154 "dataset_id": [ref.id for ref in sorted(dataset.refs)],
155 "data_id": [ref.dataId.byName() for ref in sorted(dataset.refs)],
156 "path": dataset.path,
157 "formatter": dataset.formatter,
158 # TODO: look up and save other collections
159 }
160 for dataset in datasets
161 ]
162 })
164 def saveDatasetAssociations(self, collection: str, collectionType: CollectionType,
165 associations: Iterable[DatasetAssociation]) -> None:
166 # Docstring inherited from RepoExportBackend.saveDatasetAssociations.
167 if collectionType is CollectionType.TAGGED:
168 self.data.append({
169 "type": "associations",
170 "collection": collection,
171 "collection_type": collectionType.name,
172 "dataset_ids": [assoc.ref.id for assoc in associations],
173 })
174 elif collectionType is CollectionType.CALIBRATION:
175 idsByTimespan: Dict[Timespan, List[DatasetId]] = defaultdict(list)
176 for association in associations:
177 assert association.timespan is not None
178 assert association.ref.id is not None
179 idsByTimespan[association.timespan].append(association.ref.id)
180 self.data.append({
181 "type": "associations",
182 "collection": collection,
183 "collection_type": collectionType.name,
184 "validity_ranges": [
185 {
186 "begin": timespan.begin,
187 "end": timespan.end,
188 "dataset_ids": dataset_ids,
189 }
190 for timespan, dataset_ids in idsByTimespan.items()
191 ]
192 })
194 def finish(self) -> None:
195 # Docstring inherited from RepoExportBackend.
196 yaml.dump(
197 {
198 "description": "Butler Data Repository Export",
199 "version": str(EXPORT_FORMAT_VERSION),
200 "data": self.data,
201 },
202 stream=self.stream,
203 sort_keys=False,
204 )
207class YamlRepoImportBackend(RepoImportBackend):
208 """A repository import implementation that reads from a YAML file.
210 Parameters
211 ----------
212 stream
213 A readable file-like object.
214 registry : `Registry`
215 The registry datasets will be imported into. Only used to retreive
216 dataset types during construction; all write happen in `register`
217 and `load`.
218 """
220 def __init__(self, stream: IO, registry: Registry):
221 # We read the file fully and convert its contents to Python objects
222 # instead of loading incrementally so we can spot some problems early;
223 # because `register` can't be put inside a transaction, we'd rather not
224 # run that at all if there's going to be problem later in `load`.
225 wrapper = yaml.safe_load(stream)
226 if wrapper["version"] == 0:
227 # Grandfather-in 'version: 0' -> 1.0.0, which is what we wrote
228 # before we really tried to do versioning here.
229 fileVersion = VersionTuple(1, 0, 0)
230 else:
231 fileVersion = VersionTuple.fromString(wrapper["version"])
232 if fileVersion.major != EXPORT_FORMAT_VERSION.major:
233 raise IncompatibleVersionError(
234 f"Cannot read repository export file with version={fileVersion} "
235 f"({EXPORT_FORMAT_VERSION.major}.x.x required)."
236 )
237 if fileVersion.minor > EXPORT_FORMAT_VERSION.minor:
238 raise IncompatibleVersionError(
239 f"Cannot read repository export file with version={fileVersion} "
240 f"< {EXPORT_FORMAT_VERSION.major}.{EXPORT_FORMAT_VERSION.minor}.x required."
241 )
242 self.runs: Dict[str, Tuple[Optional[str], Timespan]] = {}
243 self.chains: Dict[str, List[str]] = {}
244 self.collections: Dict[str, CollectionType] = {}
245 self.collectionDocs: Dict[str, str] = {}
246 self.datasetTypes: NamedValueSet[DatasetType] = NamedValueSet()
247 self.dimensions: Mapping[DimensionElement, List[DimensionRecord]] = defaultdict(list)
248 self.tagAssociations: Dict[str, List[DatasetId]] = defaultdict(list)
249 self.calibAssociations: Dict[str, Dict[Timespan, List[DatasetId]]] = defaultdict(dict)
250 self.refsByFileId: Dict[DatasetId, DatasetRef] = {}
251 self.registry: Registry = registry
252 datasetData = []
253 for data in wrapper["data"]:
254 if data["type"] == "dimension":
255 # convert all datetime values to astropy
256 for record in data["records"]:
257 for key in record:
258 # Some older YAML files were produced with native
259 # YAML support for datetime, we support reading that
260 # data back. Newer conversion uses _AstropyTimeToYAML
261 # class with special YAML tag.
262 if isinstance(record[key], datetime):
263 record[key] = astropy.time.Time(record[key], scale="utc")
264 element = self.registry.dimensions[data["element"]]
265 RecordClass: Type[DimensionRecord] = element.RecordClass
266 self.dimensions[element].extend(
267 RecordClass(**r) for r in data["records"]
268 )
269 elif data["type"] == "collection":
270 collectionType = CollectionType.from_name(data["collection_type"])
271 if collectionType is CollectionType.RUN:
272 self.runs[data["name"]] = (
273 data["host"],
274 Timespan(begin=data["timespan_begin"], end=data["timespan_end"])
275 )
276 elif collectionType is CollectionType.CHAINED:
277 children = []
278 for child in data["children"]:
279 if not isinstance(child, str):
280 warnings.warn(
281 f"CHAINED collection {data['name']} includes restrictions on child "
282 "collection searches, which are no longer suppored and will be ignored."
283 )
284 # Old form with dataset type restrictions only,
285 # supported for backwards compatibility.
286 child, _ = child
287 children.append(child)
288 self.chains[data["name"]] = children
289 else:
290 self.collections[data["name"]] = collectionType
291 doc = data.get("doc")
292 if doc is not None:
293 self.collectionDocs[data["name"]] = doc
294 elif data["type"] == "run":
295 # Also support old form of saving a run with no extra info.
296 self.runs[data["name"]] = (None, Timespan(None, None))
297 elif data["type"] == "dataset_type":
298 self.datasetTypes.add(
299 DatasetType(data["name"], dimensions=data["dimensions"],
300 storageClass=data["storage_class"], universe=self.registry.dimensions,
301 isCalibration=data.get("is_calibration", False))
302 )
303 elif data["type"] == "dataset":
304 # Save raw dataset data for a second loop, so we can ensure we
305 # know about all dataset types first.
306 datasetData.append(data)
307 elif data["type"] == "associations":
308 collectionType = CollectionType.from_name(data["collection_type"])
309 if collectionType is CollectionType.TAGGED:
310 self.tagAssociations[data["collection"]].extend(data["dataset_ids"])
311 elif collectionType is CollectionType.CALIBRATION:
312 assocsByTimespan = self.calibAssociations[data["collection"]]
313 for d in data["validity_ranges"]:
314 assocsByTimespan[Timespan(begin=d["begin"], end=d["end"])] = d["dataset_ids"]
315 else:
316 raise ValueError(f"Unexpected calibration type for association: {collectionType.name}.")
317 else:
318 raise ValueError(f"Unexpected dictionary type: {data['type']}.")
319 # key is (dataset type name, run)
320 self.datasets: Mapping[Tuple[str, str], List[FileDataset]] = defaultdict(list)
321 for data in datasetData:
322 datasetType = self.datasetTypes.get(data["dataset_type"])
323 if datasetType is None:
324 datasetType = self.registry.getDatasetType(data["dataset_type"])
325 self.datasets[data["dataset_type"], data["run"]].extend(
326 FileDataset(
327 d.get("path"),
328 [DatasetRef(datasetType, dataId, run=data["run"], id=refid)
329 for dataId, refid in zip(iterable(d["data_id"]), iterable(d["dataset_id"]))],
330 formatter=doImport(d.get("formatter")) if "formatter" in d else None
331 )
332 for d in data["records"]
333 )
335 def register(self) -> None:
336 # Docstring inherited from RepoImportBackend.register.
337 for datasetType in self.datasetTypes:
338 self.registry.registerDatasetType(datasetType)
339 for run in self.runs:
340 self.registry.registerRun(run, doc=self.collectionDocs.get(run))
341 # No way to add extra run info to registry yet.
342 for collection, collection_type in self.collections.items():
343 self.registry.registerCollection(collection, collection_type,
344 doc=self.collectionDocs.get(collection))
345 for chain, children in self.chains.items():
346 self.registry.registerCollection(chain, CollectionType.CHAINED,
347 doc=self.collectionDocs.get(chain))
348 self.registry.setCollectionChain(chain, children)
350 def load(self, datastore: Optional[Datastore], *,
351 directory: Optional[str] = None, transfer: Optional[str] = None,
352 skip_dimensions: Optional[Set] = None,
353 idGenerationMode: DatasetIdGenEnum = DatasetIdGenEnum.UNIQUE,
354 reuseIds: bool = False) -> None:
355 # Docstring inherited from RepoImportBackend.load.
356 for element, dimensionRecords in self.dimensions.items():
357 if skip_dimensions and element in skip_dimensions:
358 continue
359 self.registry.insertDimensionData(element, *dimensionRecords)
360 # FileDatasets to ingest into the datastore (in bulk):
361 fileDatasets = []
362 for (datasetTypeName, run), records in self.datasets.items():
363 # Make a big flattened list of all data IDs and dataset_ids, while
364 # remembering slices that associate them with the FileDataset
365 # instances they came from.
366 datasets: List[DatasetRef] = []
367 dataset_ids: List[DatasetId] = []
368 slices = []
369 for fileDataset in records:
370 start = len(datasets)
371 datasets.extend(fileDataset.refs)
372 dataset_ids.extend(ref.id for ref in fileDataset.refs) # type: ignore
373 stop = len(datasets)
374 slices.append(slice(start, stop))
375 # Insert all of those DatasetRefs at once.
376 # For now, we ignore the dataset_id we pulled from the file
377 # and just insert without one to get a new autoincrement value.
378 # Eventually (once we have origin in IDs) we'll preserve them.
379 resolvedRefs = self.registry._importDatasets(datasets, idGenerationMode=idGenerationMode,
380 reuseIds=reuseIds)
381 # Populate our dictionary that maps int dataset_id values from the
382 # export file to the new DatasetRefs
383 for fileId, ref in zip(dataset_ids, resolvedRefs):
384 self.refsByFileId[fileId] = ref
385 # Now iterate over the original records, and install the new
386 # resolved DatasetRefs to replace the unresolved ones as we
387 # reorganize the collection information.
388 for sliceForFileDataset, fileDataset in zip(slices, records):
389 fileDataset.refs = resolvedRefs[sliceForFileDataset]
390 if directory is not None:
391 fileDataset.path = ButlerURI(directory, forceDirectory=True).join(fileDataset.path)
392 fileDatasets.append(fileDataset)
393 # Ingest everything into the datastore at once.
394 if datastore is not None and fileDatasets:
395 datastore.ingest(*fileDatasets, transfer=transfer)
396 # Associate datasets with tagged collections.
397 for collection, dataset_ids in self.tagAssociations.items():
398 self.registry.associate(collection, [self.refsByFileId[i] for i in dataset_ids])
399 # Associate datasets with calibration collections.
400 for collection, idsByTimespan in self.calibAssociations.items():
401 for timespan, dataset_ids in idsByTimespan.items():
402 self.registry.certify(collection, [self.refsByFileId[i] for i in dataset_ids], timespan)