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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

# This file is part of daf_butler. 

# 

# Developed for the LSST Data Management System. 

# This product includes software developed by the LSST Project 

# (http://www.lsst.org). 

# See the COPYRIGHT file at the top-level directory of this distribution 

# for details of code ownership. 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 3 of the License, or 

# (at your option) any later version. 

# 

# This program is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

# You should have received a copy of the GNU General Public License 

# along with this program. If not, see <http://www.gnu.org/licenses/>. 

 

"""Chained datastore.""" 

 

__all__ = ("ChainedDatastore",) 

 

import time 

import logging 

import os 

import warnings 

from typing import List, Sequence, Optional 

 

from lsst.utils import doImport 

from lsst.daf.butler import Datastore, DatastoreConfig, DatasetTypeNotSupportedError, \ 

DatastoreValidationError, Constraints 

 

log = logging.getLogger(__name__) 

 

 

class ChainedDatastore(Datastore): 

"""Chained Datastores to allow read and writes from multiple datastores. 

 

A ChainedDatastore is configured with multiple datastore configurations. 

A ``put()`` is always sent to each datastore. A ``get()`` 

operation is sent to each datastore in turn and the first datastore 

to return a valid dataset is used. 

 

Parameters 

---------- 

config : `DatastoreConfig` or `str` 

Configuration. This configuration must include a ``datastores`` field 

as a sequence of datastore configurations. The order in this sequence 

indicates the order to use for read operations. 

registry : `Registry` 

Registry to use for storing internal information about the datasets. 

butlerRoot : `str`, optional 

New datastore root to use to override the configuration value. This 

root is sent to each child datastore. 

""" 

 

defaultConfigFile = "datastores/chainedDatastore.yaml" 

"""Path to configuration defaults. Relative to $DAF_BUTLER_DIR/config or 

absolute path. Can be None if no defaults specified. 

""" 

 

containerKey = "datastores" 

"""Key to specify where child datastores are configured.""" 

 

datastores: List[Datastore] 

"""All the child datastores known to this datastore.""" 

 

datastoreConstraints: Sequence[Optional[Constraints]] 

"""Constraints to be applied to each of the child datastores.""" 

 

@classmethod 

def setConfigRoot(cls, root, config, full, overwrite=True): 

"""Set any filesystem-dependent config options for child Datastores to 

be appropriate for a new empty repository with the given root. 

 

Parameters 

---------- 

root : `str` 

Filesystem path to the root of the data repository. 

config : `Config` 

A `Config` to update. Only the subset understood by 

this component will be updated. Will not expand 

defaults. 

full : `Config` 

A complete config with all defaults expanded that can be 

converted to a `DatastoreConfig`. Read-only and will not be 

modified by this method. 

Repository-specific options that should not be obtained 

from defaults when Butler instances are constructed 

should be copied from ``full`` to ``config``. 

overwrite : `bool`, optional 

If `False`, do not modify a value in ``config`` if the value 

already exists. Default is always to overwrite with the provided 

``root``. 

 

Notes 

----- 

If a keyword is explicitly defined in the supplied ``config`` it 

will not be overridden by this method if ``overwrite`` is `False`. 

This allows explicit values set in external configs to be retained. 

""" 

 

# Extract the part of the config we care about updating 

datastoreConfig = DatastoreConfig(config, mergeDefaults=False) 

 

# And the subset of the full config that we can use for reference. 

# Do not bother with defaults because we are told this already has 

# them. 

fullDatastoreConfig = DatastoreConfig(full, mergeDefaults=False) 

 

# Loop over each datastore config and pass the subsets to the 

# child datastores to process. 

 

containerKey = cls.containerKey 

for idx, (child, fullChild) in enumerate(zip(datastoreConfig[containerKey], 

fullDatastoreConfig[containerKey])): 

childConfig = DatastoreConfig(child, mergeDefaults=False) 

fullChildConfig = DatastoreConfig(fullChild, mergeDefaults=False) 

datastoreClass = doImport(fullChildConfig["cls"]) 

newroot = "{}/{}_{}".format(root, datastoreClass.__qualname__, idx) 

datastoreClass.setConfigRoot(newroot, childConfig, fullChildConfig, overwrite=overwrite) 

 

# Reattach to parent 

datastoreConfig[containerKey, idx] = childConfig 

 

# Reattach modified datastore config to parent 

# If this has a datastore key we attach there, otherwise we assume 

# this information goes at the top of the config hierarchy. 

if DatastoreConfig.component in config: 

config[DatastoreConfig.component] = datastoreConfig 

else: 

config.update(datastoreConfig) 

 

return 

 

def __init__(self, config, registry=None, butlerRoot=None): 

super().__init__(config, registry) 

 

# Scan for child datastores and instantiate them with the same registry 

self.datastores = [] 

for c in self.config["datastores"]: 

c = DatastoreConfig(c) 

datastoreType = doImport(c["cls"]) 

datastore = datastoreType(c, registry, butlerRoot=butlerRoot) 

log.debug("Creating child datastore %s", datastore.name) 

self.datastores.append(datastore) 

 

# Name ourself based on our children 

152 ↛ 155line 152 didn't jump to line 155, because the condition on line 152 was never false if self.datastores: 

childNames = ",".join([d.name for d in self.datastores]) 

else: 

childNames = "(empty@{})".format(time.time()) 

self.name = "{}[{}]".format(type(self).__qualname__, childNames) 

 

# We declare we are ephemeral if all our child datastores declare 

# they are ephemeral 

isEphemeral = True 

for d in self.datastores: 

if not d.isEphemeral: 

isEphemeral = False 

break 

self.isEphemeral = isEphemeral 

 

# per-datastore override constraints 

if "datastore_constraints" in self.config: 

overrides = self.config["datastore_constraints"] 

 

171 ↛ 172line 171 didn't jump to line 172, because the condition on line 171 was never true if len(overrides) != len(self.datastores): 

raise DatastoreValidationError(f"Number of registered datastores ({len(self.datastores)})" 

" differs from number of constraints overrides" 

f" {len(overrides)}") 

 

self.datastoreConstraints = [Constraints(c.get("constraints"), universe=self.registry.dimensions) 

for c in overrides] 

 

else: 

self.datastoreConstraints = (None,) * len(self.datastores) 

 

log.debug("Created %s (%s)", self.name, ("ephemeral" if self.isEphemeral else "permanent")) 

 

def __str__(self): 

chainName = ", ".join(str(ds) for ds in self.datastores) 

return chainName 

 

def exists(self, ref): 

"""Check if the dataset exists in one of the datastores. 

 

Parameters 

---------- 

ref : `DatasetRef` 

Reference to the required dataset. 

 

Returns 

------- 

exists : `bool` 

`True` if the entity exists in one of the child datastores. 

""" 

for datastore in self.datastores: 

if datastore.exists(ref): 

log.debug("Found %s in datastore %s", ref, datastore.name) 

return True 

return False 

 

def get(self, ref, parameters=None): 

"""Load an InMemoryDataset from the store. 

 

The dataset is returned from the first datastore that has 

the dataset. 

 

Parameters 

---------- 

ref : `DatasetRef` 

Reference to the required Dataset. 

parameters : `dict` 

`StorageClass`-specific parameters that specify, for example, 

a slice of the Dataset to be loaded. 

 

Returns 

------- 

inMemoryDataset : `object` 

Requested Dataset or slice thereof as an InMemoryDataset. 

 

Raises 

------ 

FileNotFoundError 

Requested dataset can not be retrieved. 

TypeError 

Return value from formatter has unexpected type. 

ValueError 

Formatter failed to process the dataset. 

""" 

 

for datastore in self.datastores: 

try: 

inMemoryObject = datastore.get(ref, parameters) 

log.debug("Found Dataset %s in datastore %s", ref, datastore.name) 

return inMemoryObject 

except FileNotFoundError: 

pass 

 

raise FileNotFoundError("Dataset {} could not be found in any of the datastores".format(ref)) 

 

def put(self, inMemoryDataset, ref): 

"""Write a InMemoryDataset with a given `DatasetRef` to each 

datastore. 

 

The put() to child datastores can fail with 

`DatasetTypeNotSupportedError`. The put() for this datastore will be 

deemed to have succeeded so long as at least one child datastore 

accepted the inMemoryDataset. 

 

Parameters 

---------- 

inMemoryDataset : `object` 

The Dataset to store. 

ref : `DatasetRef` 

Reference to the associated Dataset. 

 

Raises 

------ 

TypeError 

Supplied object and storage class are inconsistent. 

DatasetTypeNotSupportedError 

All datastores reported `DatasetTypeNotSupportedError`. 

""" 

log.debug("Put %s", ref) 

 

# Confirm that we can accept this dataset 

if not self.constraints.isAcceptable(ref): 

# Raise rather than use boolean return value. 

raise DatasetTypeNotSupportedError(f"Dataset {ref} has been rejected by this datastore via" 

" configuration.") 

 

isPermanent = False 

nsuccess = 0 

npermanent = 0 

nephemeral = 0 

for datastore, constraints in zip(self.datastores, self.datastoreConstraints): 

if constraints is not None and not constraints.isAcceptable(ref): 

log.debug("Datastore %s skipping put via configuration for ref %s", 

datastore.name, ref) 

continue 

 

if datastore.isEphemeral: 

nephemeral += 1 

else: 

npermanent += 1 

try: 

datastore.put(inMemoryDataset, ref) 

nsuccess += 1 

if not datastore.isEphemeral: 

isPermanent = True 

except DatasetTypeNotSupportedError: 

pass 

 

if nsuccess == 0: 

raise DatasetTypeNotSupportedError(f"None of the chained datastores supported ref {ref}") 

 

302 ↛ 303line 302 didn't jump to line 303, because the condition on line 302 was never true if not isPermanent and npermanent > 0: 

warnings.warn(f"Put of {ref} only succeeded in ephemeral databases", stacklevel=2) 

 

if self._transaction is not None: 

self._transaction.registerUndo('put', self.remove, ref) 

 

def ingest(self, path, ref, formatter=None, transfer=None): 

"""Add an on-disk file with the given `DatasetRef` to the store, 

possibly transferring it. 

 

This method is forwarded to each of the chained datastores, trapping 

cases where a datastore has not implemented file ingest and ignoring 

them. 

 

Notes 

----- 

If an absolute path is given and "move" mode is specified, then 

we tell the child datastore to use "copy" mode and unlink it 

at the end. If a relative path is given then it is assumed the file 

is already inside the child datastore. 

 

A transfer mode of None implies that the file is already within 

each of the (relevant) child datastores. 

 

Parameters 

---------- 

path : `str` 

File path. Treated as relative to the repository root of each 

child datastore if not absolute. 

ref : `DatasetRef` 

Reference to the associated Dataset. 

formatter : `Formatter` (optional) 

Formatter that should be used to retreive the Dataset. If not 

provided, the formatter will be constructed according to 

Datastore configuration. 

transfer : str (optional) 

If not None, must be one of 'move', 'copy', 'hardlink', or 

'symlink' indicating how to transfer the file. The new 

filename and location will be determined via template substitution, 

as with ``put``. If the file is outside the datastore root, it 

must be transferred somehow. 

 

Raises 

------ 

NotImplementedError 

If all chained datastores have no ingest implemented or if 

a transfer mode of `None` is specified. 

DatasetTypeNotSupportedError 

The associated `DatasetType` is not handled by this datastore. 

""" 

log.debug("Ingesting %s (transfer=%s)", ref, transfer) 

 

# Confirm that we can accept this dataset 

if not self.constraints.isAcceptable(ref): 

# Raise rather than use boolean return value. 

raise DatasetTypeNotSupportedError(f"Dataset {ref} has been rejected by this datastore via" 

" configuration.") 

 

if transfer is None: 

raise NotImplementedError("ChainedDatastore does not support transfer=None") 

 

# A "move" is sometimes a "copy" 

moveIsCopy = False 

if transfer == "move" and os.path.isabs(path): 

moveIsCopy = True 

 

notImplementedCounter = 0 

notAcceptedCounter = 0 

for datastore, constraints in zip(self.datastores, self.datastoreConstraints): 

if constraints is not None and not constraints.isAcceptable(ref): 

log.debug("Datastore %s skipping ingest via configuration for ref %s", 

datastore.name, ref) 

notAcceptedCounter += 1 

continue 

 

dstransfer = transfer 

# Each child datastore must copy the file for a move operation 

if moveIsCopy: 

dstransfer = "copy" 

try: 

datastore.ingest(path, ref, transfer=dstransfer, formatter=formatter) 

except NotImplementedError: 

notImplementedCounter += 1 

except DatasetTypeNotSupportedError: 

notAcceptedCounter += 1 

 

if (notAcceptedCounter + notImplementedCounter) == len(self.datastores): 

log.warning("Datastore %s: Not accepted counter: %d; Not implemented counter: %d for ref %s", 

self.name, notAcceptedCounter, notImplementedCounter, ref) 

if notAcceptedCounter > 0: 

raise DatasetTypeNotSupportedError(f"Ingest of {ref} not supported by the chained datastores") 

else: 

raise NotImplementedError("Ingest not implemented by any of the chained datastores") 

 

# if the file was meant to be moved then we have to delete it 

if moveIsCopy: 

os.unlink(path) 

 

def getUri(self, ref, predict=False): 

"""URI to the Dataset. 

 

The returned URI is from the first datastore in the list that has 

the dataset with preference given to the first dataset coming from 

a permanent datastore. If no datastores have the dataset and prediction 

is allowed, the predicted URI for the first datastore in the list will 

be returned. 

 

Parameters 

---------- 

ref : `DatasetRef` 

Reference to the required Dataset. 

predict : `bool` 

If `True`, allow URIs to be returned of datasets that have not 

been written. 

 

Returns 

------- 

uri : `str` 

URI string pointing to the Dataset within the datastore. If the 

Dataset does not exist in the datastore, and if ``predict`` is 

`True`, the URI will be a prediction and will include a URI 

fragment "#predicted". 

 

Notes 

----- 

If the datastore does not have entities that relate well 

to the concept of a URI the returned URI string will be 

descriptive. The returned URI is not guaranteed to be obtainable. 

 

Raises 

------ 

FileNotFoundError 

A URI has been requested for a dataset that does not exist and 

guessing is not allowed. 

""" 

log.debug("Requesting URI for %s", ref) 

predictedUri = None 

predictedEphemeralUri = None 

firstEphemeralUri = None 

for datastore in self.datastores: 

if datastore.exists(ref): 

if not datastore.isEphemeral: 

uri = datastore.getUri(ref) 

log.debug("Retrieved ephemeral URI: %s", uri) 

return uri 

elif firstEphemeralUri is None: 

firstEphemeralUri = datastore.getUri(ref) 

elif predict: 

if predictedUri is None and not datastore.isEphemeral: 

predictedUri = datastore.getUri(ref, predict) 

elif predictedEphemeralUri is None and datastore.isEphemeral: 

predictedEphemeralUri = datastore.getUri(ref, predict) 

 

if firstEphemeralUri is not None: 

log.debug("Retrieved ephemeral URI: %s", firstEphemeralUri) 

return firstEphemeralUri 

 

if predictedUri is not None: 

log.debug("Retrieved predicted URI: %s", predictedUri) 

return predictedUri 

 

if predictedEphemeralUri is not None: 

log.debug("Retrieved predicted ephemeral URI: %s", predictedEphemeralUri) 

return predictedEphemeralUri 

 

raise FileNotFoundError("Dataset {} not in any datastore".format(ref)) 

 

def remove(self, ref): 

"""Indicate to the Datastore that a Dataset can be removed. 

 

The dataset will be removed from each datastore. The dataset is 

not required to exist in every child datastore. 

 

Parameters 

---------- 

ref : `DatasetRef` 

Reference to the required Dataset. 

 

Raises 

------ 

FileNotFoundError 

Attempt to remove a dataset that does not exist. Raised if none 

of the child datastores removed the dataset. 

""" 

log.debug(f"Removing {ref}") 

 

counter = 0 

for datastore in self.datastores: 

try: 

datastore.remove(ref) 

counter += 1 

except FileNotFoundError: 

pass 

 

if counter == 0: 

raise FileNotFoundError(f"Could not remove from any child datastore: {ref}") 

 

def transfer(self, inputDatastore, ref): 

"""Retrieve a Dataset from an input `Datastore`, 

and store the result in this `Datastore`. 

 

Parameters 

---------- 

inputDatastore : `Datastore` 

The external `Datastore` from which to retreive the Dataset. 

ref : `DatasetRef` 

Reference to the required Dataset in the input data store. 

 

Returns 

------- 

results : `list` 

List containing the return value from the ``put()`` to each 

child datastore. 

""" 

assert inputDatastore is not self # unless we want it for renames? 

inMemoryDataset = inputDatastore.get(ref) 

return [datastore.put(inMemoryDataset, ref) for datastore in self.datastores] 

 

def validateConfiguration(self, entities, logFailures=False): 

"""Validate some of the configuration for this datastore. 

 

Parameters 

---------- 

entities : iterable of `DatasetRef`, `DatasetType`, or `StorageClass` 

Entities to test against this configuration. Can be differing 

types. 

logFailures : `bool`, optional 

If `True`, output a log message for every validation error 

detected. 

 

Raises 

------ 

DatastoreValidationError 

Raised if there is a validation problem with a configuration. 

All the problems are reported in a single exception. 

 

Notes 

----- 

This method checks each datastore in turn. 

""" 

 

# Need to catch each of the datastore outputs and ensure that 

# all are tested. 

failures = [] 

for datastore in self.datastores: 

try: 

datastore.validateConfiguration(entities, logFailures=logFailures) 

except DatastoreValidationError as e: 

550 ↛ 552line 550 didn't jump to line 552, because the condition on line 550 was never false if logFailures: 

log.fatal("Datastore %s failed validation", datastore.name) 

failures.append(f"Datastore {self.name}: {e}") 

 

if failures: 

msg = ";\n".join(failures) 

raise DatastoreValidationError(msg) 

 

def validateKey(self, lookupKey, entity): 

# Docstring is inherited from base class 

failures = [] 

for datastore in self.datastores: 

try: 

datastore.validateKey(lookupKey, entity) 

except DatastoreValidationError as e: 

failures.append(f"Datastore {self.name}: {e}") 

 

if failures: 

msg = ";\n".join(failures) 

raise DatastoreValidationError(msg) 

 

def getLookupKeys(self): 

# Docstring is inherited from base class 

keys = set() 

for datastore in self.datastores: 

keys.update(datastore.getLookupKeys()) 

 

keys.update(self.constraints.getLookupKeys()) 

for p in self.datastoreConstraints: 

579 ↛ 580line 579 didn't jump to line 580, because the condition on line 579 was never true if p is not None: 

keys.update(p.getLookupKeys()) 

 

return keys