Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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 

22 

23__all__ = ("DatastoreRegistryBridgeManager", "DatastoreRegistryBridge", "FakeDatasetRef", "DatasetIdRef") 

24 

25from abc import ABC, abstractmethod 

26from typing import ( 

27 Any, 

28 ContextManager, 

29 Iterable, 

30 Type, 

31 TYPE_CHECKING, 

32 Union, 

33) 

34 

35from ...core.utils import immutable 

36from ...core import DatasetRef 

37from ._versioning import VersionedExtension 

38 

39if TYPE_CHECKING: 39 ↛ 40line 39 didn't jump to line 40, because the condition on line 39 was never true

40 from ...core import DatasetType, DimensionUniverse 

41 from ._database import Database, StaticTablesContext 

42 from ._datasets import DatasetRecordStorageManager 

43 from ._opaque import OpaqueTableStorageManager 

44 

45 

46@immutable 

47class FakeDatasetRef: 

48 """A fake `DatasetRef` that can be used internally by butler where 

49 only the dataset ID is available. 

50 

51 Should only be used when registry can not be used to create a full 

52 `DatasetRef` from the ID. A particular use case is during dataset 

53 deletion when solely the ID is available. 

54 

55 Parameters 

56 ---------- 

57 id : `int` 

58 The dataset ID. 

59 """ 

60 __slots__ = ("id",) 

61 

62 def __init__(self, id: int): 

63 self.id = id 

64 

65 def __str__(self) -> str: 

66 return f"dataset_id={self.id}" 

67 

68 def __repr__(self) -> str: 

69 return f"FakeDatasetRef({self.id})" 

70 

71 def __eq__(self, other: Any) -> bool: 

72 try: 

73 return self.id == other.id 

74 except AttributeError: 

75 return NotImplemented 

76 

77 def __hash__(self) -> int: 

78 return hash(self.id) 

79 

80 id: int 

81 """Unique integer that identifies this dataset. 

82 """ 

83 

84 def getCheckedId(self) -> int: 

85 """Return ``self.id``. 

86 

87 This trivial method exists for compatibility with `DatasetRef`, for 

88 which checking is actually done. 

89 

90 Returns 

91 ------- 

92 id : `int` 

93 ``self.id``. 

94 """ 

95 return self.id 

96 

97 @property 

98 def datasetType(self) -> DatasetType: 

99 raise AttributeError("A FakeDatasetRef can not be associated with a valid DatasetType") 

100 

101 

102DatasetIdRef = Union[DatasetRef, FakeDatasetRef] 

103"""A type-annotation alias that matches both `DatasetRef` and `FakeDatasetRef`. 

104""" 

105 

106 

107class DatastoreRegistryBridge(ABC): 

108 """An abstract base class that defines the interface that a `Datastore` 

109 uses to communicate with a `Registry`. 

110 

111 Parameters 

112 ---------- 

113 datastoreName : `str` 

114 Name of the `Datastore` as it should appear in `Registry` tables 

115 referencing it. 

116 """ 

117 def __init__(self, datastoreName: str): 

118 self.datastoreName = datastoreName 

119 

120 @abstractmethod 

121 def insert(self, refs: Iterable[DatasetIdRef]) -> None: 

122 """Record that a datastore holds the given datasets. 

123 

124 Parameters 

125 ---------- 

126 refs : `Iterable` of `DatasetIdRef` 

127 References to the datasets. 

128 

129 Raises 

130 ------ 

131 AmbiguousDatasetError 

132 Raised if ``any(ref.id is None for ref in refs)``. 

133 """ 

134 raise NotImplementedError() 

135 

136 @abstractmethod 

137 def forget(self, refs: Iterable[DatasetIdRef]) -> None: 

138 """Remove dataset location information without any attempt to put it 

139 in the trash while waiting for external deletes. 

140 

141 This should be used only to implement `Datastore.forget`, or in cases 

142 where deleting the actual datastore artifacts cannot fail. 

143 

144 Parameters 

145 ---------- 

146 refs : `Iterable` of `DatasetIdRef` 

147 References to the datasets. 

148 

149 Raises 

150 ------ 

151 AmbiguousDatasetError 

152 Raised if ``any(ref.id is None for ref in refs)``. 

153 """ 

154 raise NotImplementedError() 

155 

156 @abstractmethod 

157 def moveToTrash(self, refs: Iterable[DatasetIdRef]) -> None: 

158 """Move dataset location information to trash. 

159 

160 Parameters 

161 ---------- 

162 refs : `Iterable` of `DatasetIdRef` 

163 References to the datasets. 

164 

165 Raises 

166 ------ 

167 AmbiguousDatasetError 

168 Raised if ``any(ref.id is None for ref in refs)``. 

169 """ 

170 raise NotImplementedError() 

171 

172 @abstractmethod 

173 def check(self, refs: Iterable[DatasetIdRef]) -> Iterable[DatasetIdRef]: 

174 """Check which refs are listed for this datastore. 

175 

176 Parameters 

177 ---------- 

178 refs : `~collections.abc.Iterable` of `DatasetIdRef` 

179 References to the datasets. 

180 

181 Returns 

182 ------- 

183 present : `Iterable` [ `DatasetIdRef` ] 

184 Datasets from ``refs`` that are recorded as being in this 

185 datastore. 

186 

187 Raises 

188 ------ 

189 AmbiguousDatasetError 

190 Raised if ``any(ref.id is None for ref in refs)``. 

191 """ 

192 raise NotImplementedError() 

193 

194 @abstractmethod 

195 def emptyTrash(self) -> ContextManager[Iterable[DatasetIdRef]]: 

196 """Retrieve all the dataset ref IDs that are in the trash 

197 associated for this datastore, and then remove them if the context 

198 exists without an exception being raised. 

199 

200 Returns 

201 ------- 

202 ids : `set` of `DatasetIdRef` 

203 The IDs of datasets that can be safely removed from this datastore. 

204 Can be empty. 

205 

206 Examples 

207 -------- 

208 Typical usage by a Datastore is something like:: 

209 

210 with self.bridge.emptyTrash() as iter: 

211 for ref in iter: 

212 # Remove artifacts associated with ref.id, 

213 # raise an exception if something goes wrong. 

214 

215 Notes 

216 ----- 

217 The object yielded by the context manager may be a single-pass 

218 iterator. If multiple passes are required, it should be converted to 

219 a `list` or other container. 

220 

221 Datastores should never raise (except perhaps in testing) when an 

222 artifact cannot be removed only because it is already gone - this 

223 condition is an unavoidable outcome of concurrent delete operations, 

224 and must not be considered and error for those to be safe. 

225 """ 

226 raise NotImplementedError() 

227 

228 datastoreName: str 

229 """The name of the `Datastore` as it should appear in `Registry` tables 

230 (`str`). 

231 """ 

232 

233 

234class DatastoreRegistryBridgeManager(VersionedExtension): 

235 """An abstract base class that defines the interface between `Registry` 

236 and `Datastore` when a new `Datastore` is constructed. 

237 

238 Parameters 

239 ---------- 

240 opaque : `OpaqueTableStorageManager` 

241 Manager object for opaque table storage in the `Registry`. 

242 universe : `DimensionUniverse` 

243 All dimensions know to the `Registry`. 

244 

245 Notes 

246 ----- 

247 Datastores are passed an instance of `DatastoreRegistryBridgeManager` at 

248 construction, and should use it to obtain and keep any of the following: 

249 

250 - a `DatastoreRegistryBridge` instance to record in the `Registry` what is 

251 present in the datastore (needed by all datastores that are not just 

252 forwarders); 

253 

254 - one or more `OpaqueTableStorage` instance if they wish to store internal 

255 records in the `Registry` database; 

256 

257 - the `DimensionUniverse`, if they need it to (e.g.) construct or validate 

258 filename templates. 

259 

260 """ 

261 def __init__(self, *, opaque: OpaqueTableStorageManager, universe: DimensionUniverse): 

262 self.opaque = opaque 

263 self.universe = universe 

264 

265 @classmethod 

266 @abstractmethod 

267 def initialize(cls, db: Database, context: StaticTablesContext, *, 

268 opaque: OpaqueTableStorageManager, 

269 datasets: Type[DatasetRecordStorageManager], 

270 universe: DimensionUniverse, 

271 ) -> DatastoreRegistryBridgeManager: 

272 """Construct an instance of the manager. 

273 

274 Parameters 

275 ---------- 

276 db : `Database` 

277 Interface to the underlying database engine and namespace. 

278 context : `StaticTablesContext` 

279 Context object obtained from `Database.declareStaticTables`; used 

280 to declare any tables that should always be present in a layer 

281 implemented with this manager. 

282 opaque : `OpaqueTableStorageManager` 

283 Registry manager object for opaque (to Registry) tables, provided 

284 to allow Datastores to store their internal information inside the 

285 Registry database. 

286 datasets : subclass of `DatasetRecordStorageManager` 

287 Concrete class that will be used to manage the core dataset tables 

288 in this registry; should be used only to create foreign keys to 

289 those tables. 

290 universe : `DimensionUniverse` 

291 All dimensions known to the registry. 

292 

293 Returns 

294 ------- 

295 manager : `DatastoreRegistryBridgeManager` 

296 An instance of a concrete `DatastoreRegistryBridgeManager` 

297 subclass. 

298 """ 

299 raise NotImplementedError() 

300 

301 @abstractmethod 

302 def refresh(self) -> None: 

303 """Ensure all other operations on this manager are aware of any 

304 collections that may have been registered by other clients since it 

305 was initialized or last refreshed. 

306 """ 

307 raise NotImplementedError() 

308 

309 @abstractmethod 

310 def register(self, name: str, *, ephemeral: bool = True) -> DatastoreRegistryBridge: 

311 """Register a new `Datastore` associated with this `Registry`. 

312 

313 This method should be called by all `Datastore` classes aside from 

314 those that only forward storage to other datastores. 

315 

316 Parameters 

317 ---------- 

318 name : `str` 

319 Name of the datastore, as it should appear in `Registry` tables. 

320 ephemeral : `bool`, optional 

321 If `True` (`False` is default), return a bridge object that is 

322 backed by storage that will not last past the end of the current 

323 process. This should be used whenever the same is true of the 

324 dataset's artifacts. 

325 

326 Returns 

327 ------- 

328 bridge : `DatastoreRegistryBridge` 

329 Object that provides the interface this `Datastore` should use to 

330 communicate with the `Regitry`. 

331 """ 

332 raise NotImplementedError() 

333 

334 @abstractmethod 

335 def findDatastores(self, ref: DatasetRef) -> Iterable[str]: 

336 """Retrieve datastore locations for a given dataset. 

337 

338 Parameters 

339 ---------- 

340 ref : `DatasetRef` 

341 A reference to the dataset for which to retrieve storage 

342 information. 

343 

344 Returns 

345 ------- 

346 datastores : `Iterable` [ `str` ] 

347 All the matching datastores holding this dataset. Empty if the 

348 dataset does not exist anywhere. 

349 

350 Raises 

351 ------ 

352 AmbiguousDatasetError 

353 Raised if ``ref.id`` is `None`. 

354 """ 

355 raise NotImplementedError() 

356 

357 opaque: OpaqueTableStorageManager 

358 """Registry manager object for opaque (to Registry) tables, provided 

359 to allow Datastores to store their internal information inside the 

360 Registry database. 

361 """ 

362 

363 universe: DimensionUniverse 

364 """All dimensions known to the `Registry`. 

365 """