download.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import collections
  2. from dataclasses import dataclass, field
  3. import glob
  4. import hashlib
  5. import json
  6. from pathlib import Path
  7. import requests
  8. import shutil
  9. import tempfile
  10. from typing import List, Optional
  11. from .config import Arch, LinuxTag
  12. from ..utils.log import debug, log
  13. CHUNK_SIZE = 8189
  14. SUCCESS = 200
  15. class DownloadError(Exception):
  16. pass
  17. class TarError(Exception):
  18. pass
  19. @dataclass(frozen=True)
  20. class Downloader:
  21. '''Manylinux tag.'''
  22. tag: LinuxTag
  23. '''Platform architecture.'''
  24. arch: Optional[Arch] = None
  25. '''Docker image.'''
  26. image: str = field(init=False)
  27. '''Authentication token.'''
  28. token: str = field(init=False)
  29. def __post_init__(self):
  30. # Set host arch if not explictly specified.
  31. if self.arch is None:
  32. arch = Arch.from_host()
  33. object.__setattr__(self, 'arch', arch)
  34. # Set image name.
  35. image = f'{self.tag}_{self.arch}'
  36. object.__setattr__(self, 'image', image)
  37. def download(
  38. self,
  39. destination: Optional[Path]=None,
  40. tag: Optional[str] = 'latest'):
  41. destination = destination or Path(self.image)
  42. # Authenticate to quay.io.
  43. repository = f'pypa/{self.image}'
  44. url = 'https://quay.io/v2/auth'
  45. url = f'{url}?service=quay.io&scope=repository:{repository}:pull'
  46. debug('GET', url)
  47. r = requests.request('GET', url)
  48. if r.status_code == SUCCESS:
  49. object.__setattr__(self, 'token', r.json()['token'])
  50. else:
  51. raise DownloadError(r.status_code, r.text, r.headers)
  52. # Fetch image manifest.
  53. repository = f'pypa/{self.image}'
  54. url = f'https://quay.io/v2/{repository}/manifests/{tag}'
  55. headers = {
  56. 'Authorization': f'Bearer {self.token}',
  57. 'Accept': 'application/vnd.docker.distribution.manifest.v2+json'
  58. }
  59. debug('GET', url)
  60. r = requests.request('GET', url, headers=headers)
  61. if r.status_code == SUCCESS:
  62. image_digest = r.headers['Docker-Content-Digest'].split(':', 1)[-1]
  63. manifest = r.json()
  64. else:
  65. raise DownloadError(r.status_code, r.text, r.headers)
  66. # Check missing layers to download.
  67. required = [layer['digest'].split(':', 1)[-1] for layer in
  68. manifest['layers']]
  69. is_missing = lambda hash_: \
  70. not (destination / f'layers/{hash_}.tar.gz').exists()
  71. missing = tuple(filter(is_missing, required))
  72. # Fetch missing layers.
  73. with tempfile.TemporaryDirectory() as tmpdir:
  74. workdir = Path(tmpdir)
  75. for i, hash_ in enumerate(missing):
  76. log('DOWNLOAD', f'{self.image} ({tag}) '
  77. f'[{i + 1} / {len(missing)}]')
  78. filename = f'{hash_}.tar.gz'
  79. url = f'https://quay.io/v2/{repository}/blobs/sha256:{hash_}'
  80. debug('GET', url)
  81. r = requests.request('GET', url, headers=headers, stream=True)
  82. if r.status_code == SUCCESS:
  83. debug('STREAM', filename)
  84. else:
  85. raise DownloadError(r.status_code, r.text, r.headers)
  86. hasher = hashlib.sha256()
  87. tmp = workdir / 'layer.tgz'
  88. with open(tmp, "wb") as f:
  89. for chunk in r.iter_content(CHUNK_SIZE):
  90. if chunk:
  91. f.write(chunk)
  92. hasher.update(chunk)
  93. h = hasher.hexdigest()
  94. if h != hash_:
  95. raise DownloadError(
  96. f'bad hash (expected {name}, found {h})'
  97. )
  98. layers_dir = destination / 'layers'
  99. layers_dir.mkdir(exist_ok=True, parents=True)
  100. shutil.move(tmp, layers_dir / filename)
  101. tags_dir = destination / 'tags'
  102. tags_dir.mkdir(exist_ok=True, parents=True)
  103. with open(tags_dir / f'{tag}.json', "w") as f:
  104. json.dump({'digest': image_digest, 'layers': required}, f)
  105. # Remove unused layers.
  106. required = set(required)
  107. for tag in glob.glob(str(destination / 'tags/*.json')):
  108. with open(tag) as f:
  109. tag = json.load(f)
  110. required |= set(tag["layers"])
  111. required = [f'{hash_}.tar.gz' for hash_ in required]
  112. for layer in glob.glob(str(destination / 'layers/*.tar.gz')):
  113. layer = Path(layer)
  114. if layer.name not in required:
  115. debug('REMOVE', f'{self.image} [layer/{layer.stem}]')
  116. layer.unlink()