Coverage for src/rok4/storage.py: 80%

543 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-01 12:58 +0000

1"""Provide functions to read or write data 

2 

3Available storage types are : 

4 

5- S3 (path are preffixed with `s3://`) 

6- CEPH (path are prefixed with `ceph://`) 

7- FILE (path are prefixed with `file://`, but it is the default paths' interpretation) 

8- HTTP (path are prefixed with `http://`) 

9- HTTPS (path are prefixed with `https://`) 

10 

11According to functions, all storage types are not necessarily available. 

12 

13Readings uses a LRU cache system with a TTL. It's possible to configure it with environment variables : 

14 

15- ROK4_READING_LRU_CACHE_SIZE : Number of cached element. Default 64. Set 0 or a negative integer to configure a cache without bound. A power of two make cache more efficient. 

16- ROK4_READING_LRU_CACHE_TTL : Validity duration of cached element, in seconds. Default 300. 0 or negative integer to get cache without expiration date. 

17 

18To disable cache (always read data on storage), set ROK4_READING_LRU_CACHE_SIZE to 1 and ROK4_READING_LRU_CACHE_TTL to 1. 

19 

20Using CEPH storage requires environment variables : 

21 

22- ROK4_CEPH_CONFFILE 

23- ROK4_CEPH_USERNAME 

24- ROK4_CEPH_CLUSTERNAME 

25 

26Using S3 storage requires environment variables : 

27 

28- ROK4_S3_KEY 

29- ROK4_S3_SECRETKEY 

30- ROK4_S3_URL 

31- ROK4_S3_REGION (optional) 

32 

33To use several S3 clusters, each environment variable have to contain a list (comma-separated), with the same number of elements 

34 

35Example, work with 2 S3 clusters: 

36 

37- ROK4_S3_KEY=KEY1,KEY2 

38- ROK4_S3_SECRETKEY=SKEY1,SKEY2 

39- ROK4_S3_URL=https://s3.storage.fr,https://s4.storage.fr 

40- ROK4_S3_REGION=region1,region2 

41 

42 

43To precise the cluster to use, bucket name should be bucket_name@s3.storage.fr or bucket_name@s4.storage.fr. If no host is defined (no @) in the bucket name, first S3 cluster is used 

44""" 

45 

46import hashlib 

47import os 

48import re 

49import tempfile 

50import time 

51from functools import lru_cache 

52from shutil import copyfile 

53from typing import Dict, Tuple, Union 

54 

55import boto3 

56import botocore.exceptions 

57import requests 

58 

59# conditional import 

60 

61try: 

62 from osgeo import gdal 

63 

64 # Enable GDAL/OGR exceptions 

65 gdal.UseExceptions() 

66 

67 GDAL_AVAILABLE: bool = True 

68except ImportError: 

69 GDAL_AVAILABLE: bool = False 

70 gdal = None 

71 

72 

73try: 

74 import rados 

75 

76 CEPH_RADOS_AVAILABLE: bool = True 

77except ImportError: 

78 CEPH_RADOS_AVAILABLE: bool = False 

79 rados = None 

80 

81# package 

82from rok4.enums import StorageType 

83from rok4.exceptions import MissingEnvironmentError, StorageError 

84 

85# -- GLOBALS -- 

86 

87 

88__CEPH_CLIENT = None 

89__CEPH_IOCTXS = {} 

90__OBJECT_SYMLINK_SIGNATURE = "SYMLINK#" 

91__S3_CLIENTS = {} 

92__S3_DEFAULT_CLIENT = None 

93__LRU_SIZE = 64 

94__LRU_TTL = 300 

95 

96try: 

97 __LRU_SIZE = int(os.environ["ROK4_READING_LRU_CACHE_SIZE"]) 

98 if __LRU_SIZE < 1: 

99 __LRU_SIZE = None 

100except ValueError: 

101 pass 

102except KeyError: 

103 pass 

104 

105try: 

106 __LRU_TTL = int(os.environ["ROK4_READING_LRU_CACHE_TTL"]) 

107 __LRU_TTL = max(__LRU_TTL, 0) 

108except ValueError: 

109 pass 

110except KeyError: 

111 pass 

112 

113 

114def __get_ttl_hash() -> int: 

115 """Return the time string rounded according to time-to-live value""" 

116 if __LRU_TTL == 0: 

117 return 0 

118 else: 

119 return round(time.time() / __LRU_TTL) 

120 

121 

122def __get_s3_client(bucket_name: str) -> Tuple[Dict[str, Union["boto3.client", str]], str, str]: 

123 """Get the S3 client 

124 

125 Create it if not already done 

126 

127 Args: 

128 bucket_name (str): S3 bucket name. Could be just the bucket name, or <bucket name>@<cluster host> 

129 

130 Raises: 

131 MissingEnvironmentError: Missing S3 storage informations 

132 StorageError: S3 client configuration issue 

133 

134 Returns: 

135 Tuple[Dict[str, Union['boto3.client',str]], str]: the S3 informations (client, host, key, secret) and the simple bucket name 

136 """ 

137 

138 global __S3_CLIENTS, __S3_DEFAULT_CLIENT 

139 

140 if not __S3_CLIENTS: 

141 verify = True 

142 if "ROK4_SSL_NO_VERIFY" in os.environ and os.environ["ROK4_SSL_NO_VERIFY"] != "": 

143 verify = False 

144 # C'est la première fois qu'on cherche à utiliser le stockage S3, chargeons les informations depuis les variables d'environnement 

145 try: 

146 keys = os.environ["ROK4_S3_KEY"].split(",") 

147 secret_keys = os.environ["ROK4_S3_SECRETKEY"].split(",") 

148 urls = os.environ["ROK4_S3_URL"].split(",") 

149 # ROK4_S3_REGION est optionnelle : None est utilisé pour les clusters sans région définie 

150 if os.environ.get("ROK4_S3_REGION", "") != "": 

151 regions = os.environ["ROK4_S3_REGION"].split(",") 

152 else: 

153 regions = [None] * len(keys) 

154 

155 if len(keys) != len(secret_keys) or len(keys) != len(urls) or len(keys) != len(regions): 

156 raise StorageError( 

157 "S3", 

158 "S3 informations in environment variables are inconsistent : same number of element in each list is required", 

159 ) 

160 

161 for i in range(len(keys)): 

162 h = re.sub("https?://", "", urls[i]) 

163 

164 if h in __S3_CLIENTS: 

165 raise StorageError("S3", "A S3 cluster is defined twice (based on URL)") 

166 

167 __S3_CLIENTS[h] = { 

168 "client": boto3.client( 

169 "s3", 

170 aws_access_key_id=keys[i], 

171 aws_secret_access_key=secret_keys[i], 

172 verify=verify, 

173 endpoint_url=urls[i], 

174 region_name=regions[i], 

175 config=botocore.config.Config(tcp_keepalive=True, max_pool_connections=10), 

176 ), 

177 "key": keys[i], 

178 "secret_key": secret_keys[i], 

179 "url": urls[i], 

180 "host": h, 

181 "secure": urls[i].startswith("https://"), 

182 } 

183 

184 if i == 0: 

185 # Le premier cluster est celui par défaut 

186 __S3_DEFAULT_CLIENT = h 

187 

188 except KeyError as e: 

189 raise MissingEnvironmentError(e) 

190 except Exception as e: 

191 raise StorageError("S3", e) 

192 

193 try: 

194 host = bucket_name.split("@")[1] 

195 except IndexError: 

196 host = __S3_DEFAULT_CLIENT 

197 

198 bucket_name = bucket_name.split("@")[0] 

199 

200 if host not in __S3_CLIENTS: 

201 raise StorageError("S3", f"Unknown S3 cluster, according to host '{host}'") 

202 

203 return __S3_CLIENTS[host], bucket_name 

204 

205 

206def disconnect_s3_clients() -> None: 

207 """Clean S3 clients""" 

208 

209 global __S3_CLIENTS, __S3_DEFAULT_CLIENT 

210 __S3_CLIENTS = {} 

211 __S3_DEFAULT_CLIENT = None 

212 

213 

214def __get_ceph_ioctx(pool: str) -> "rados.Ioctx": 

215 """Get the CEPH IO context 

216 

217 Create it (client and context) if not already done 

218 

219 Args: 

220 pool (str): CEPH pool's name 

221 

222 Raises: 

223 MissingEnvironmentError: Missing CEPH storage informations 

224 StorageError: CEPH IO context configuration issue 

225 

226 Returns: 

227 rados.Ioctx: IO ceph context 

228 """ 

229 global __CEPH_CLIENT, __CEPH_IOCTXS 

230 

231 if __CEPH_CLIENT is None: 

232 try: 

233 __CEPH_CLIENT = rados.Rados( 

234 conffile=os.environ["ROK4_CEPH_CONFFILE"], 

235 clustername=os.environ["ROK4_CEPH_CLUSTERNAME"], 

236 name=os.environ["ROK4_CEPH_USERNAME"], 

237 ) 

238 

239 __CEPH_CLIENT.connect() 

240 

241 except KeyError as e: 

242 raise MissingEnvironmentError(e) 

243 except Exception as e: 

244 raise StorageError("CEPH", e) 

245 

246 if pool not in __CEPH_IOCTXS: 

247 try: 

248 __CEPH_IOCTXS[pool] = __CEPH_CLIENT.open_ioctx(pool) 

249 except Exception as e: 

250 raise StorageError("CEPH", e) 

251 

252 return __CEPH_IOCTXS[pool] 

253 

254 

255def disconnect_ceph_clients() -> None: 

256 """Clean CEPH clients""" 

257 global __CEPH_CLIENT, __CEPH_IOCTXS 

258 __CEPH_CLIENT = None 

259 __CEPH_IOCTXS = {} 

260 

261 

262def get_infos_from_path(path: str) -> Tuple[StorageType, str, str, str]: 

263 """Extract storage type, the unprefixed path, the container and the basename from path (Default: FILE storage) 

264 

265 For a FILE storage, the tray is the directory and the basename is the file name. 

266 

267 For an object storage (CEPH or S3), the tray is the bucket or the pool and the basename is the object name. 

268 For a S3 bucket, format can be <bucket name>@<cluster name> to use several clusters. Cluster name is the host (without protocol) 

269 

270 Args: 

271 path (str): path to analyse 

272 

273 Returns: 

274 Tuple[StorageType, str, str, str]: storage type, unprefixed path, the container and the basename 

275 """ 

276 

277 if path.startswith("s3://"): 

278 bucket_name, object_name = path[5:].split("/", 1) 

279 return StorageType.S3, path[5:], bucket_name, object_name 

280 elif path.startswith("ceph://"): 

281 pool_name, object_name = path[7:].split("/", 1) 

282 return StorageType.CEPH, path[7:], pool_name, object_name 

283 elif path.startswith("file://"): 

284 return StorageType.FILE, path[7:], os.path.dirname(path[7:]), os.path.basename(path[7:]) 

285 elif path.startswith("http://"): 

286 return StorageType.HTTP, path[7:], os.path.dirname(path[7:]), os.path.basename(path[7:]) 

287 elif path.startswith("https://"): 

288 return StorageType.HTTPS, path[8:], os.path.dirname(path[8:]), os.path.basename(path[8:]) 

289 else: 

290 return StorageType.FILE, path, os.path.dirname(path), os.path.basename(path) 

291 

292 

293def get_path_from_infos(storage_type: StorageType, *args) -> str: 

294 """Write full path from elements 

295 

296 Prefixed wih storage's type, elements are joined with a slash 

297 

298 Args: 

299 storage_type (StorageType): Storage's type for path 

300 

301 Returns: 

302 str: Full path 

303 """ 

304 return f"{storage_type.value}{os.path.join(*args)}" 

305 

306 

307def hash_file(path: str) -> str: 

308 """Process MD5 sum of the provided file 

309 

310 Args: 

311 path (str): path to file 

312 

313 Returns: 

314 str: hexadeimal MD5 sum 

315 """ 

316 

317 checker = hashlib.md5() 

318 

319 with open(path, "rb") as file: 

320 chunk = 0 

321 while chunk != b"": 

322 chunk = file.read(65536) 

323 checker.update(chunk) 

324 

325 return checker.hexdigest() 

326 

327 

328def get_data_str(path: str) -> str: 

329 """Load full data into a string 

330 

331 Args: 

332 path (str): path to data 

333 

334 Raises: 

335 MissingEnvironmentError: Missing object storage informations 

336 StorageError: Storage read issue 

337 FileNotFoundError: File or object does not exist 

338 NotImplementedError: Storage type not handled 

339 

340 Returns: 

341 str: Data content 

342 """ 

343 

344 return get_data_binary(path).decode("utf-8") 

345 

346 

347@lru_cache(maxsize=__LRU_SIZE) 

348def __get_cached_data_binary(path: str, ttl_hash: int, range: Tuple[int, int] = None) -> str: 

349 """Load data into a binary string, using a LRU cache 

350 

351 Args: 

352 path (str): path to data 

353 ttl_hash (int): time hash, to invalid cache 

354 range (Tuple[int, int], optional): offset and size, to make a partial read. Defaults to None. 

355 

356 Raises: 

357 MissingEnvironmentError: Missing object storage informations 

358 StorageError: Storage read issue 

359 FileNotFoundError: File or object does not exist 

360 NotImplementedError: Storage type not handled 

361 

362 Returns: 

363 str: Data binary content 

364 """ 

365 storage_type, path, tray_name, base_name = get_infos_from_path(path) 

366 

367 if storage_type == StorageType.S3: 

368 s3_client, bucket_name = __get_s3_client(tray_name) 

369 

370 try: 

371 if range is None: 

372 data = ( 

373 s3_client["client"] 

374 .get_object( 

375 Bucket=bucket_name, 

376 Key=base_name, 

377 )["Body"] 

378 .read() 

379 ) 

380 else: 

381 data = ( 

382 s3_client["client"] 

383 .get_object( 

384 Bucket=bucket_name, 

385 Key=base_name, 

386 Range=f"bytes={range[0]}-{range[0] + range[1] - 1}", 

387 )["Body"] 

388 .read() 

389 ) 

390 

391 except botocore.exceptions.ClientError as e: 

392 if e.response["Error"]["Code"] == "NoSuchKey": 

393 raise FileNotFoundError(f"{storage_type.value}{path}") 

394 else: 

395 raise StorageError("S3", e) 

396 

397 except Exception as e: 

398 raise StorageError("S3", e) 

399 

400 elif storage_type == StorageType.CEPH and CEPH_RADOS_AVAILABLE: 

401 ioctx = __get_ceph_ioctx(tray_name) 

402 

403 try: 

404 if range is None: 

405 size, mtime = ioctx.stat(base_name) 

406 data = ioctx.read(base_name, size) 

407 else: 

408 data = ioctx.read(base_name, range[1], range[0]) 

409 

410 except rados.ObjectNotFound: 

411 raise FileNotFoundError(f"{storage_type.value}{path}") 

412 

413 except Exception as e: 

414 raise StorageError("CEPH", e) 

415 

416 elif storage_type == StorageType.FILE: 

417 try: 

418 f = open(path, "rb") 

419 if range is None: 

420 data = f.read() 

421 else: 

422 f.seek(range[0]) 

423 data = f.read(range[1]) 

424 

425 f.close() 

426 

427 except FileNotFoundError: 

428 raise FileNotFoundError(f"{storage_type.value}{path}") 

429 

430 except Exception as e: 

431 raise StorageError("FILE", e) 

432 

433 elif storage_type == StorageType.HTTP or storage_type == StorageType.HTTPS: 

434 if range is None: 

435 try: 

436 reponse = requests.get(f"{storage_type.value}{path}", stream=True) 

437 data = reponse.content 

438 if reponse.status_code == 404: 

439 raise FileNotFoundError(f"{storage_type.value}{path}") 

440 except Exception as e: 

441 raise StorageError(storage_type.name, e) 

442 else: 

443 raise NotImplementedError("Cannot get partial data for storage type HTTP(S)") 

444 

445 else: 

446 raise NotImplementedError(f"Cannot get data for storage type {storage_type.name}") 

447 

448 return data 

449 

450 

451def get_data_binary(path: str, range: Tuple[int, int] = None) -> str: 

452 """Load data into a binary string 

453 

454 This function uses a LRU cache, with a TTL of 5 minutes 

455 

456 Args: 

457 path (str): path to data 

458 range (Tuple[int, int], optional): offset and size, to make a partial read. Defaults to None. 

459 

460 Raises: 

461 MissingEnvironmentError: Missing object storage informations 

462 StorageError: Storage read issue 

463 FileNotFoundError: File or object does not exist 

464 NotImplementedError: Storage type not handled 

465 

466 Returns: 

467 str: Data binary content 

468 """ 

469 return __get_cached_data_binary(path, __get_ttl_hash(), range) 

470 

471 

472def put_data_str(data: str, path: str) -> None: 

473 """Store string data into a file or an object 

474 

475 UTF-8 encoding is used for bytes conversion 

476 

477 Args: 

478 data (str): data to write 

479 path (str): destination path, where to write data 

480 

481 Raises: 

482 MissingEnvironmentError: Missing object storage informations 

483 StorageError: Storage write issue 

484 NotImplementedError: Storage type not handled 

485 """ 

486 

487 storage_type, path, tray_name, base_name = get_infos_from_path(path) 

488 

489 if storage_type == StorageType.S3: 

490 s3_client, bucket_name = __get_s3_client(tray_name) 

491 

492 try: 

493 s3_client["client"].put_object( 

494 Body=data.encode("utf-8"), Bucket=bucket_name, Key=base_name 

495 ) 

496 except Exception as e: 

497 raise StorageError("S3", e) 

498 

499 elif storage_type == StorageType.CEPH and CEPH_RADOS_AVAILABLE: 

500 ioctx = __get_ceph_ioctx(tray_name) 

501 

502 try: 

503 ioctx.write_full(base_name, data.encode("utf-8")) 

504 except Exception as e: 

505 raise StorageError("CEPH", e) 

506 

507 elif storage_type == StorageType.FILE: 

508 try: 

509 f = open(path, "w") 

510 f.write(data) 

511 f.close() 

512 except Exception as e: 

513 raise StorageError("FILE", e) 

514 

515 else: 

516 raise NotImplementedError(f"Cannot write data for storage type {storage_type.name}") 

517 

518 

519def get_size(path: str) -> int: 

520 """Get size of file or object 

521 

522 Args: 

523 path (str): path of file/object whom size is asked 

524 

525 Raises: 

526 MissingEnvironmentError: Missing object storage informations 

527 StorageError: Storage read issue 

528 NotImplementedError: Storage type not handled 

529 

530 Returns: 

531 int: file/object size, in bytes 

532 """ 

533 

534 storage_type, path, tray_name, base_name = get_infos_from_path(path) 

535 

536 if storage_type == StorageType.S3: 

537 s3_client, bucket_name = __get_s3_client(tray_name) 

538 

539 try: 

540 size = s3_client["client"].head_object(Bucket=bucket_name, Key=base_name)[ 

541 "ContentLength" 

542 ] 

543 return int(size) 

544 except Exception as e: 

545 raise StorageError("S3", e) 

546 

547 elif storage_type == StorageType.CEPH and CEPH_RADOS_AVAILABLE: 

548 ioctx = __get_ceph_ioctx(tray_name) 

549 

550 try: 

551 size, mtime = ioctx.stat(base_name) 

552 return size 

553 except Exception as e: 

554 raise StorageError("CEPH", e) 

555 

556 elif storage_type == StorageType.FILE: 

557 try: 

558 file_stats = os.stat(path) 

559 return file_stats.st_size 

560 except Exception as e: 

561 raise StorageError("FILE", e) 

562 

563 elif storage_type == StorageType.HTTP or storage_type == StorageType.HTTPS: 

564 try: 

565 # Le stream=True permet de ne télécharger que le header initialement 

566 reponse = requests.get(storage_type.value + path, stream=True).headers["content-length"] 

567 return reponse 

568 except Exception as e: 

569 raise StorageError(storage_type.name, e) 

570 

571 else: 

572 raise NotImplementedError(f"Cannot get size for storage type {storage_type.name}") 

573 

574 

575def exists(path: str) -> bool: 

576 """Do the file or object exist ? 

577 

578 Args: 

579 path (str): path of file/object to test 

580 

581 Raises: 

582 MissingEnvironmentError: Missing object storage informations 

583 StorageError: Storage read issue 

584 NotImplementedError: Storage type not handled 

585 

586 Returns: 

587 bool: file/object existing status 

588 """ 

589 

590 storage_type, path, tray_name, base_name = get_infos_from_path(path) 

591 

592 if storage_type == StorageType.S3: 

593 s3_client, bucket_name = __get_s3_client(tray_name) 

594 

595 try: 

596 s3_client["client"].head_object(Bucket=bucket_name, Key=base_name) 

597 return True 

598 except botocore.exceptions.ClientError as e: 

599 if e.response["Error"]["Code"] == "404": 

600 return False 

601 else: 

602 raise StorageError("S3", e) 

603 

604 elif storage_type == StorageType.CEPH and CEPH_RADOS_AVAILABLE: 

605 ioctx = __get_ceph_ioctx(tray_name) 

606 

607 try: 

608 ioctx.stat(base_name) 

609 return True 

610 except rados.ObjectNotFound: 

611 return False 

612 except Exception as e: 

613 raise StorageError("CEPH", e) 

614 

615 elif storage_type == StorageType.FILE: 

616 return os.path.exists(path) 

617 

618 elif storage_type == StorageType.HTTP or storage_type == StorageType.HTTPS: 

619 try: 

620 response = requests.get(storage_type.value + path, stream=True) 

621 if response.status_code == 200: 

622 return True 

623 else: 

624 return False 

625 except Exception as e: 

626 raise StorageError(storage_type.name, e) 

627 

628 else: 

629 raise NotImplementedError(f"Cannot test existence for storage type {storage_type.name}") 

630 

631 

632def remove(path: str) -> None: 

633 """Remove the file/object 

634 

635 Args: 

636 path (str): path of file/object to remove 

637 

638 Raises: 

639 MissingEnvironmentError: Missing object storage informations 

640 StorageError: Storage removal issue 

641 NotImplementedError: Storage type not handled 

642 """ 

643 storage_type, path, tray_name, base_name = get_infos_from_path(path) 

644 

645 if storage_type == StorageType.S3: 

646 s3_client, bucket_name = __get_s3_client(tray_name) 

647 

648 try: 

649 s3_client["client"].delete_object(Bucket=bucket_name, Key=base_name) 

650 except Exception as e: 

651 raise StorageError("S3", e) 

652 

653 elif storage_type == StorageType.CEPH and CEPH_RADOS_AVAILABLE: 

654 ioctx = __get_ceph_ioctx(tray_name) 

655 

656 try: 

657 ioctx.remove_object(base_name) 

658 except rados.ObjectNotFound: 

659 pass 

660 except Exception as e: 

661 raise StorageError("CEPH", e) 

662 

663 elif storage_type == StorageType.FILE: 

664 try: 

665 os.remove(path) 

666 except FileNotFoundError: 

667 pass 

668 except Exception as e: 

669 raise StorageError("FILE", e) 

670 

671 else: 

672 raise NotImplementedError(f"Cannot remove data for storage type {storage_type.name}") 

673 

674 

675def copy(from_path: str, to_path: str, from_md5: str = None) -> None: 

676 """Copy a file or object to a file or object place. If MD5 sum is provided, it is compared to sum after the copy. 

677 

678 Args: 

679 from_path (str): source file/object path, to copy 

680 to_path (str): destination file/object path 

681 from_md5 (str, optional): MD5 sum, re-processed after copy and controlled. Defaults to None. 

682 

683 Raises: 

684 StorageError: Copy issue 

685 MissingEnvironmentError: Missing object storage informations 

686 NotImplementedError: Storage type not handled 

687 """ 

688 

689 from_type, from_path, from_tray, from_base_name = get_infos_from_path(from_path) 

690 to_type, to_path, to_tray, to_base_name = get_infos_from_path(to_path) 

691 

692 # Réalisation de la copie, selon les types de stockage 

693 if from_type == StorageType.FILE and to_type == StorageType.FILE: 

694 try: 

695 if to_tray != "": 

696 os.makedirs(to_tray, exist_ok=True) 

697 

698 copyfile(from_path, to_path) 

699 

700 if from_md5 is not None: 

701 to_md5 = hash_file(to_path) 

702 if to_md5 != from_md5: 

703 raise StorageError( 

704 "FILE", 

705 f"Invalid MD5 sum control for copy file {from_path} to {to_path} : {from_md5} != {to_md5}", 

706 ) 

707 

708 except Exception as e: 

709 raise StorageError("FILE", f"Cannot copy file {from_path} to {to_path} : {e}") 

710 

711 elif from_type == StorageType.S3 and to_type == StorageType.FILE: 

712 s3_client, from_bucket = __get_s3_client(from_tray) 

713 

714 try: 

715 if to_tray != "": 

716 os.makedirs(to_tray, exist_ok=True) 

717 

718 s3_client["client"].download_file(from_bucket, from_base_name, to_path) 

719 

720 if from_md5 is not None: 

721 to_md5 = hash_file(to_path) 

722 if to_md5 != from_md5: 

723 raise StorageError( 

724 "S3 and FILE", 

725 f"Invalid MD5 sum control for copy S3 object {from_path} to file {to_path} : {from_md5} != {to_md5}", 

726 ) 

727 

728 except Exception as e: 

729 raise StorageError( 

730 "S3 and FILE", f"Cannot copy S3 object {from_path} to file {to_path} : {e}" 

731 ) 

732 

733 elif from_type == StorageType.FILE and to_type == StorageType.S3: 

734 s3_client, to_bucket = __get_s3_client(to_tray) 

735 

736 try: 

737 s3_client["client"].upload_file(from_path, to_bucket, to_base_name) 

738 

739 if from_md5 is not None: 

740 to_md5 = ( 

741 s3_client["client"] 

742 .head_object(Bucket=to_bucket, Key=to_base_name)["ETag"] 

743 .strip('"') 

744 ) 

745 if to_md5 != from_md5: 

746 raise StorageError( 

747 "FILE and S3", 

748 f"Invalid MD5 sum control for copy file {from_path} to S3 object {to_path} : {from_md5} != {to_md5}", 

749 ) 

750 except Exception as e: 

751 raise StorageError( 

752 "FILE and S3", f"Cannot copy file {from_path} to S3 object {to_path} : {e}" 

753 ) 

754 

755 elif from_type == StorageType.S3 and to_type == StorageType.S3: 

756 from_s3_client, from_bucket = __get_s3_client(from_tray) 

757 to_s3_client, to_bucket = __get_s3_client(to_tray) 

758 

759 try: 

760 if to_s3_client["host"] == from_s3_client["host"]: 

761 to_s3_client["client"].copy( 

762 {"Bucket": from_bucket, "Key": from_base_name}, to_bucket, to_base_name 

763 ) 

764 else: 

765 with tempfile.NamedTemporaryFile("w+b") as f: 

766 from_s3_client["client"].download_fileobj(from_bucket, from_base_name, f) 

767 to_s3_client["client"].upload_file(f.name, to_bucket, to_base_name) 

768 

769 if from_md5 is not None: 

770 to_md5 = ( 

771 to_s3_client["client"] 

772 .head_object(Bucket=to_bucket, Key=to_base_name)["ETag"] 

773 .strip('"') 

774 ) 

775 if to_md5 != from_md5: 

776 raise StorageError( 

777 "S3", 

778 f"Invalid MD5 sum control for copy S3 object {from_path} to {to_path} : {from_md5} != {to_md5}", 

779 ) 

780 

781 except Exception as e: 

782 raise StorageError("S3", f"Cannot copy S3 object {from_path} to {to_path} : {e}") 

783 

784 elif from_type == StorageType.CEPH and CEPH_RADOS_AVAILABLE and to_type == StorageType.FILE: 

785 ioctx = __get_ceph_ioctx(from_tray) 

786 

787 if from_md5 is not None: 

788 checker = hashlib.md5() 

789 

790 try: 

791 if to_tray != "": 

792 os.makedirs(to_tray, exist_ok=True) 

793 f = open(to_path, "wb") 

794 

795 offset = 0 

796 size = 0 

797 

798 while True: 

799 chunk = ioctx.read(from_base_name, 65536, offset) 

800 size = len(chunk) 

801 offset += size 

802 f.write(chunk) 

803 

804 if from_md5 is not None: 

805 checker.update(chunk) 

806 

807 if size < 65536: 

808 break 

809 

810 f.close() 

811 

812 if from_md5 is not None and from_md5 != checker.hexdigest(): 

813 raise StorageError( 

814 "CEPH and FILE", 

815 f"Invalid MD5 sum control for copy CEPH object {from_path} to file {to_path} : {from_md5} != {checker.hexdigest()}", 

816 ) 

817 

818 except Exception as e: 

819 raise StorageError( 

820 "CEPH and FILE", f"Cannot copy CEPH object {from_path} to file {to_path} : {e}" 

821 ) 

822 

823 elif from_type == StorageType.FILE and to_type == StorageType.CEPH and CEPH_RADOS_AVAILABLE: 

824 ioctx = __get_ceph_ioctx(to_tray) 

825 

826 if from_md5 is not None: 

827 checker = hashlib.md5() 

828 

829 try: 

830 f = open(from_path, "rb") 

831 

832 offset = 0 

833 size = 0 

834 

835 while True: 

836 chunk = f.read(65536) 

837 size = len(chunk) 

838 ioctx.write(to_base_name, chunk, offset) 

839 offset += size 

840 

841 if from_md5 is not None: 

842 checker.update(chunk) 

843 

844 if size < 65536: 

845 break 

846 

847 f.close() 

848 

849 if from_md5 is not None and from_md5 != checker.hexdigest(): 

850 raise StorageError( 

851 "FILE and CEPH", 

852 f"Invalid MD5 sum control for copy file {from_path} to CEPH object {to_path} : {from_md5} != {checker.hexdigest()}", 

853 ) 

854 

855 except Exception as e: 

856 raise StorageError( 

857 "FILE and CEPH", f"Cannot copy file {from_path} to CEPH object {to_path} : {e}" 

858 ) 

859 

860 elif from_type == StorageType.CEPH and to_type == StorageType.CEPH and CEPH_RADOS_AVAILABLE: 

861 from_ioctx = __get_ceph_ioctx(from_tray) 

862 to_ioctx = __get_ceph_ioctx(to_tray) 

863 

864 if from_md5 is not None: 

865 checker = hashlib.md5() 

866 

867 try: 

868 offset = 0 

869 size = 0 

870 

871 while True: 

872 chunk = from_ioctx.read(from_base_name, 65536, offset) 

873 size = len(chunk) 

874 to_ioctx.write(to_base_name, chunk, offset) 

875 offset += size 

876 

877 if from_md5 is not None: 

878 checker.update(chunk) 

879 

880 if size < 65536: 

881 break 

882 

883 if from_md5 is not None and from_md5 != checker.hexdigest(): 

884 raise StorageError( 

885 "FILE and CEPH", 

886 f"Invalid MD5 sum control for copy CEPH object {from_path} to {to_path} : {from_md5} != {checker.hexdigest()}", 

887 ) 

888 

889 except Exception as e: 

890 raise StorageError("CEPH", f"Cannot copy CEPH object {from_path} to {to_path} : {e}") 

891 

892 elif from_type == StorageType.CEPH and CEPH_RADOS_AVAILABLE and to_type == StorageType.S3: 

893 from_ioctx = __get_ceph_ioctx(from_tray) 

894 

895 s3_client, to_bucket = __get_s3_client(to_tray) 

896 

897 if from_md5 is not None: 

898 checker = hashlib.md5() 

899 

900 try: 

901 offset = 0 

902 size = 0 

903 

904 with tempfile.NamedTemporaryFile("w+b", delete=False) as f: 

905 name_tmp = f.name 

906 while True: 

907 chunk = from_ioctx.read(from_base_name, 65536, offset) 

908 size = len(chunk) 

909 offset += size 

910 f.write(chunk) 

911 

912 if from_md5 is not None: 

913 checker.update(chunk) 

914 

915 if size < 65536: 

916 break 

917 

918 s3_client["client"].upload_file(name_tmp, to_bucket, to_base_name) 

919 

920 os.remove(name_tmp) 

921 

922 if from_md5 is not None and from_md5 != checker.hexdigest(): 

923 raise StorageError( 

924 "CEPH and S3", 

925 f"Invalid MD5 sum control for copy CEPH object {from_path} to S3 object {to_path} : {from_md5} != {checker.hexdigest()}", 

926 ) 

927 

928 except Exception as e: 

929 raise StorageError( 

930 "CEPH and S3", f"Cannot copy CEPH object {from_path} to S3 object {to_path} : {e}" 

931 ) 

932 

933 elif ( 

934 from_type == StorageType.HTTP or from_type == StorageType.HTTPS 

935 ) and to_type == StorageType.FILE: 

936 try: 

937 response = requests.get(from_type.value + from_path, stream=True) 

938 with open(to_path, "wb") as f: 

939 for chunk in response.iter_content(chunk_size=65536): 

940 if chunk: 

941 f.write(chunk) 

942 

943 except Exception as e: 

944 raise StorageError( 

945 "HTTP(S) and FILE", 

946 f"Cannot copy HTTP(S) object {from_path} to FILE object {to_path} : {e}", 

947 ) 

948 

949 elif ( 

950 (from_type == StorageType.HTTP or from_type == StorageType.HTTPS) 

951 and to_type == StorageType.CEPH 

952 and CEPH_RADOS_AVAILABLE 

953 ): 

954 to_ioctx = __get_ceph_ioctx(to_tray) 

955 

956 try: 

957 response = requests.get(from_type.value + from_path, stream=True) 

958 offset = 0 

959 for chunk in response.iter_content(chunk_size=65536): 

960 if chunk: 

961 size = len(chunk) 

962 to_ioctx.write(to_base_name, chunk, offset) 

963 offset += size 

964 

965 except Exception as e: 

966 raise StorageError( 

967 "HTTP(S) and CEPH", 

968 f"Cannot copy HTTP(S) object {from_path} to CEPH object {to_path} : {e}", 

969 ) 

970 

971 elif ( 

972 from_type == StorageType.HTTP or from_type == StorageType.HTTPS 

973 ) and to_type == StorageType.S3: 

974 to_s3_client, to_bucket = __get_s3_client(to_tray) 

975 

976 try: 

977 response = requests.get(from_type.value + from_path, stream=True) 

978 with tempfile.NamedTemporaryFile("w+b", delete=False) as f: 

979 name_fich = f.name 

980 for chunk in response.iter_content(chunk_size=65536): 

981 if chunk: 

982 f.write(chunk) 

983 

984 to_s3_client["client"].upload_file(name_fich, to_tray, to_base_name) 

985 

986 os.remove(name_fich) 

987 

988 except Exception as e: 

989 raise StorageError( 

990 "HTTP(S) and S3", 

991 f"Cannot copy HTTP(S) object {from_path} to S3 object {to_path} : {e}", 

992 ) 

993 

994 else: 

995 raise NotImplementedError( 

996 f"Cannot copy data from storage type {from_type.name} to storage type {to_type.name}" 

997 ) 

998 

999 

1000def link(target_path: str, link_path: str, hard: bool = False) -> None: 

1001 """Create a symbolic link 

1002 

1003 Args: 

1004 target_path (str): file/object to link 

1005 link_path (str): link to create 

1006 hard (bool, optional): hard link rather than symbolic. Only for FILE storage. Defaults to False. 

1007 

1008 Raises: 

1009 StorageError: link issue 

1010 MissingEnvironmentError: Missing object storage informations 

1011 NotImplementedError: Storage type not handled 

1012 """ 

1013 

1014 target_type, target_path, target_tray, target_base_name = get_infos_from_path(target_path) 

1015 link_type, link_path, link_tray, link_base_name = get_infos_from_path(link_path) 

1016 

1017 if target_type != link_type: 

1018 raise StorageError( 

1019 f"{target_type.name} and {link_type.name}", 

1020 "Cannot make link between two different storage types", 

1021 ) 

1022 

1023 if hard and target_type != StorageType.FILE: 

1024 raise StorageError(target_type.name, "Hard link is available only for FILE storage") 

1025 

1026 # Réalisation du lien, selon les types de stockage 

1027 if target_type == StorageType.S3: 

1028 target_s3_client, target_bucket = __get_s3_client(target_tray) 

1029 link_s3_client, link_bucket = __get_s3_client(link_tray) 

1030 

1031 if target_s3_client["host"] != link_s3_client["host"]: 

1032 raise StorageError( 

1033 "S3", 

1034 f"Cannot make link {link_path} -> {target_path} : link works only on the same S3 cluster", 

1035 ) 

1036 

1037 try: 

1038 target_s3_client["client"].put_object( 

1039 Body=f"{__OBJECT_SYMLINK_SIGNATURE}{target_bucket}/{target_base_name}".encode(), 

1040 Bucket=link_bucket, 

1041 Key=link_base_name, 

1042 ) 

1043 except Exception as e: 

1044 raise StorageError("S3", e) 

1045 

1046 elif target_type == StorageType.CEPH and CEPH_RADOS_AVAILABLE: 

1047 ioctx = __get_ceph_ioctx(link_tray) 

1048 

1049 try: 

1050 ioctx.write_full(link_base_name, f"{__OBJECT_SYMLINK_SIGNATURE}{target_path}".encode()) 

1051 except Exception as e: 

1052 raise StorageError("CEPH", e) 

1053 

1054 elif target_type == StorageType.FILE: 

1055 try: 

1056 to_tray = get_infos_from_path(link_path)[2] 

1057 if to_tray != "": 

1058 os.makedirs(to_tray, exist_ok=True) 

1059 

1060 if exists(link_path): 

1061 remove(link_path) 

1062 if hard: 

1063 os.link(target_path, link_path) 

1064 else: 

1065 os.symlink(target_path, link_path) 

1066 except Exception as e: 

1067 raise StorageError("FILE", e) 

1068 

1069 else: 

1070 raise NotImplementedError(f"Cannot make link for storage type {target_type.name}") 

1071 

1072 

1073def get_osgeo_path(path: str) -> str: 

1074 """Return GDAL/OGR Open compliant path and configure storage access 

1075 

1076 For a S3 input path, endpoint, access and secret keys are set and path is built with "/vsis3" root. 

1077 

1078 For a FILE input path, only storage prefix is removed 

1079 

1080 Args: 

1081 path (str): Source path 

1082 

1083 Raises: 

1084 NotImplementedError: Storage type not handled 

1085 

1086 Returns: 

1087 str: GDAL/OGR Open compliant path 

1088 """ 

1089 

1090 storage_type, unprefixed_path, tray_name, base_name = get_infos_from_path(path) 

1091 

1092 if storage_type == StorageType.S3 and GDAL_AVAILABLE: 

1093 s3_client, bucket_name = __get_s3_client(tray_name) 

1094 

1095 gdal.SetConfigOption("AWS_SECRET_ACCESS_KEY", s3_client["secret_key"]) 

1096 gdal.SetConfigOption("AWS_ACCESS_KEY_ID", s3_client["key"]) 

1097 gdal.SetConfigOption("AWS_S3_ENDPOINT", s3_client["host"]) 

1098 gdal.SetConfigOption("AWS_VIRTUAL_HOSTING", "FALSE") 

1099 if not s3_client["secure"]: 

1100 gdal.SetConfigOption("AWS_HTTPS", "NO") 

1101 

1102 return f"/vsis3/{bucket_name}/{base_name}" 

1103 

1104 elif storage_type == StorageType.FILE: 

1105 return unprefixed_path 

1106 

1107 else: 

1108 raise NotImplementedError(f"Cannot get a GDAL/OGR compliant path from {path}") 

1109 

1110 

1111def size_path(path: str) -> int: 

1112 """Return the size of the given path (or, for the CEPH, the sum of the size of each object of the .list) 

1113 

1114 Args: 

1115 path (str): Source path 

1116 

1117 Raises: 

1118 StorageError: Unhandled link or link issue 

1119 MissingEnvironmentError: Missing object storage informations 

1120 NotImplementedError: Storage type not handled 

1121 

1122 Returns: 

1123 int: size of the path 

1124 """ 

1125 storage_type, unprefixed_path, tray_name, base_name = get_infos_from_path(path) 

1126 

1127 if storage_type == StorageType.FILE: 

1128 try: 

1129 total = 0 

1130 with os.scandir(unprefixed_path) as it: 

1131 for entry in it: 

1132 if entry.is_file(): 

1133 total += entry.stat().st_size 

1134 elif entry.is_dir(): 

1135 total += size_path(entry.path) 

1136 

1137 except Exception as e: 

1138 raise StorageError("FILE", e) 

1139 

1140 elif storage_type == StorageType.S3: 

1141 s3_client, bucket_name = __get_s3_client(tray_name) 

1142 

1143 try: 

1144 paginator = s3_client["client"].get_paginator("list_objects_v2") 

1145 pages = paginator.paginate( 

1146 Bucket=bucket_name, 

1147 Prefix=base_name + "/", 

1148 PaginationConfig={ 

1149 "PageSize": 10000, 

1150 }, 

1151 ) 

1152 total = 0 

1153 for page in pages: 

1154 for key in page["Contents"]: 

1155 total += key["Size"] 

1156 

1157 except Exception as e: 

1158 raise StorageError("S3", e) 

1159 

1160 else: 

1161 raise NotImplementedError( 

1162 f"Cannot get prefix path size for storage type {storage_type.name}" 

1163 ) 

1164 

1165 return total