| 1 |
#!/usr/bin/python3 -u |
| 2 |
# This Source Code Form is subject to the terms of the Mozilla Public |
| 3 |
# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 4 |
# file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 |
|
| 6 |
import argparse |
| 7 |
import bz2 |
| 8 |
import concurrent.futures |
| 9 |
import contextlib |
| 10 |
import datetime |
| 11 |
import gzip |
| 12 |
import hashlib |
| 13 |
import io |
| 14 |
import json |
| 15 |
import lzma |
| 16 |
import multiprocessing |
| 17 |
import os |
| 18 |
import pathlib |
| 19 |
import random |
| 20 |
import re |
| 21 |
import ssl |
| 22 |
import stat |
| 23 |
import subprocess |
| 24 |
import sys |
| 25 |
import tarfile |
| 26 |
import tempfile |
| 27 |
import time |
| 28 |
import urllib.parse |
| 29 |
import urllib.request |
| 30 |
import zipfile |
| 31 |
|
| 32 |
try: |
| 33 |
import zstandard |
| 34 |
except ImportError: |
| 35 |
zstandard = None |
| 36 |
|
| 37 |
try: |
| 38 |
import certifi |
| 39 |
except ImportError: |
| 40 |
certifi = None |
| 41 |
|
| 42 |
|
| 43 |
CONCURRENCY = multiprocessing.cpu_count() |
| 44 |
|
| 45 |
|
| 46 |
def log(msg): |
| 47 |
print(msg, file=sys.stderr) |
| 48 |
sys.stderr.flush() |
| 49 |
|
| 50 |
|
| 51 |
class IntegrityError(Exception): |
| 52 |
"""Represents an integrity error when downloading a URL.""" |
| 53 |
|
| 54 |
|
| 55 |
def ZstdCompressor(*args, **kwargs): |
| 56 |
if not zstandard: |
| 57 |
raise ValueError("zstandard Python package not available") |
| 58 |
return zstandard.ZstdCompressor(*args, **kwargs) |
| 59 |
|
| 60 |
|
| 61 |
def ZstdDecompressor(*args, **kwargs): |
| 62 |
if not zstandard: |
| 63 |
raise ValueError("zstandard Python package not available") |
| 64 |
return zstandard.ZstdDecompressor(*args, **kwargs) |
| 65 |
|
| 66 |
|
| 67 |
@contextlib.contextmanager |
| 68 |
def rename_after_close(fname, *args, **kwargs): |
| 69 |
""" |
| 70 |
Context manager that opens a temporary file to use as a writer, |
| 71 |
and closes the file on context exit, renaming it to the expected |
| 72 |
file name in case of success, or removing it in case of failure. |
| 73 |
|
| 74 |
Takes the same options as open(), but must be used as a context |
| 75 |
manager. |
| 76 |
""" |
| 77 |
path = pathlib.Path(fname) |
| 78 |
tmp = path.with_name("%s.tmp" % path.name) |
| 79 |
try: |
| 80 |
with tmp.open(*args, **kwargs) as fh: |
| 81 |
yield fh |
| 82 |
except Exception: |
| 83 |
tmp.unlink() |
| 84 |
raise |
| 85 |
else: |
| 86 |
tmp.rename(fname) |
| 87 |
|
| 88 |
|
| 89 |
# The following is copied from |
| 90 |
# https://github.com/mozilla-releng/redo/blob/6d07678a014e0c525e54a860381a165d34db10ff/redo/__init__.py#L15-L85 |
| 91 |
def retrier(attempts=5, sleeptime=10, max_sleeptime=300, sleepscale=1.5, jitter=1): |
| 92 |
""" |
| 93 |
A generator function that sleeps between retries, handles exponential |
| 94 |
backoff and jitter. The action you are retrying is meant to run after |
| 95 |
retrier yields. |
| 96 |
|
| 97 |
At each iteration, we sleep for sleeptime + random.randint(-jitter, jitter). |
| 98 |
Afterwards sleeptime is multiplied by sleepscale for the next iteration. |
| 99 |
|
| 100 |
Args: |
| 101 |
attempts (int): maximum number of times to try; defaults to 5 |
| 102 |
sleeptime (float): how many seconds to sleep between tries; defaults to |
| 103 |
60s (one minute) |
| 104 |
max_sleeptime (float): the longest we'll sleep, in seconds; defaults to |
| 105 |
300s (five minutes) |
| 106 |
sleepscale (float): how much to multiply the sleep time by each |
| 107 |
iteration; defaults to 1.5 |
| 108 |
jitter (int): random jitter to introduce to sleep time each iteration. |
| 109 |
the amount is chosen at random between [-jitter, +jitter] |
| 110 |
defaults to 1 |
| 111 |
|
| 112 |
Yields: |
| 113 |
None, a maximum of `attempts` number of times |
| 114 |
|
| 115 |
Example: |
| 116 |
>>> n = 0 |
| 117 |
>>> for _ in retrier(sleeptime=0, jitter=0): |
| 118 |
... if n == 3: |
| 119 |
... # We did the thing! |
| 120 |
... break |
| 121 |
... n += 1 |
| 122 |
>>> n |
| 123 |
3 |
| 124 |
|
| 125 |
>>> n = 0 |
| 126 |
>>> for _ in retrier(sleeptime=0, jitter=0): |
| 127 |
... if n == 6: |
| 128 |
... # We did the thing! |
| 129 |
... break |
| 130 |
... n += 1 |
| 131 |
... else: |
| 132 |
... print("max tries hit") |
| 133 |
max tries hit |
| 134 |
""" |
| 135 |
jitter = jitter or 0 # py35 barfs on the next line if jitter is None |
| 136 |
if jitter > sleeptime: |
| 137 |
# To prevent negative sleep times |
| 138 |
raise Exception( |
| 139 |
"jitter ({}) must be less than sleep time ({})".format(jitter, sleeptime) |
| 140 |
) |
| 141 |
|
| 142 |
sleeptime_real = sleeptime |
| 143 |
for _ in range(attempts): |
| 144 |
log("attempt %i/%i" % (_ + 1, attempts)) |
| 145 |
|
| 146 |
yield sleeptime_real |
| 147 |
|
| 148 |
if jitter: |
| 149 |
sleeptime_real = sleeptime + random.randint(-jitter, jitter) |
| 150 |
# our jitter should scale along with the sleeptime |
| 151 |
jitter = int(jitter * sleepscale) |
| 152 |
else: |
| 153 |
sleeptime_real = sleeptime |
| 154 |
|
| 155 |
sleeptime *= sleepscale |
| 156 |
|
| 157 |
if sleeptime_real > max_sleeptime: |
| 158 |
sleeptime_real = max_sleeptime |
| 159 |
|
| 160 |
# Don't need to sleep the last time |
| 161 |
if _ < attempts - 1: |
| 162 |
log( |
| 163 |
"sleeping for %.2fs (attempt %i/%i)" % (sleeptime_real, _ + 1, attempts) |
| 164 |
) |
| 165 |
time.sleep(sleeptime_real) |
| 166 |
|
| 167 |
|
| 168 |
def stream_download(url, sha256=None, size=None, headers=None): |
| 169 |
"""Download a URL to a generator, optionally with content verification. |
| 170 |
|
| 171 |
If ``sha256`` or ``size`` are defined, the downloaded URL will be |
| 172 |
validated against those requirements and ``IntegrityError`` will be |
| 173 |
raised if expectations do not match. |
| 174 |
|
| 175 |
Because verification cannot occur until the file is completely downloaded |
| 176 |
it is recommended for consumers to not do anything meaningful with the |
| 177 |
data if content verification is being used. To securely handle retrieved |
| 178 |
content, it should be streamed to a file or memory and only operated |
| 179 |
on after the generator is exhausted without raising. |
| 180 |
""" |
| 181 |
log("Downloading %s" % url) |
| 182 |
headers = headers or [] |
| 183 |
|
| 184 |
h = hashlib.sha256() |
| 185 |
length = 0 |
| 186 |
|
| 187 |
t0 = time.time() |
| 188 |
req_headers = {} |
| 189 |
for header in headers: |
| 190 |
key, val = header.split(":") |
| 191 |
req_headers[key.strip()] = val.strip() |
| 192 |
|
| 193 |
req = urllib.request.Request(url, None, req_headers) |
| 194 |
kwargs = {} |
| 195 |
if certifi: |
| 196 |
ssl_context = ssl.create_default_context(cafile=certifi.where()) |
| 197 |
kwargs["context"] = context = ssl_context |
| 198 |
with urllib.request.urlopen(req, timeout=60, **kwargs) as fh: |
| 199 |
if not url.endswith(".gz") and fh.info().get("Content-Encoding") == "gzip": |
| 200 |
fh = gzip.GzipFile(fileobj=fh) |
| 201 |
else: |
| 202 |
# when using gzip we can't compare size or length (inflated) against content-length (compressed) |
| 203 |
content_length = fh.getheader("content-length") |
| 204 |
if content_length: |
| 205 |
try: |
| 206 |
content_length = int(content_length) |
| 207 |
except ValueError: |
| 208 |
raise IntegrityError( |
| 209 |
"content-length header for %s is not an integer; got %s" |
| 210 |
% (url, content_length) |
| 211 |
) |
| 212 |
if size: |
| 213 |
if size != content_length: |
| 214 |
raise IntegrityError( |
| 215 |
"size mismatch on %s: wanted %d; content-length is %d, x-cache-status is: %s" |
| 216 |
% ( |
| 217 |
url, |
| 218 |
size, |
| 219 |
content_length, |
| 220 |
fh.getheader("x-cache-status"), |
| 221 |
) |
| 222 |
) |
| 223 |
else: |
| 224 |
size = content_length |
| 225 |
|
| 226 |
while True: |
| 227 |
chunk = fh.read(65536) |
| 228 |
if not chunk: |
| 229 |
break |
| 230 |
|
| 231 |
h.update(chunk) |
| 232 |
length += len(chunk) |
| 233 |
|
| 234 |
yield chunk |
| 235 |
|
| 236 |
duration = time.time() - t0 |
| 237 |
digest = h.hexdigest() |
| 238 |
|
| 239 |
log( |
| 240 |
"%s resolved to %d bytes with sha256 %s in %.3fs" |
| 241 |
% (url, length, digest, duration) |
| 242 |
) |
| 243 |
|
| 244 |
if size: |
| 245 |
if size == length: |
| 246 |
log("Verified size of %s" % url) |
| 247 |
else: |
| 248 |
raise IntegrityError( |
| 249 |
"size mismatch on %s: wanted %d; got %d" % (url, size, length) |
| 250 |
) |
| 251 |
|
| 252 |
if sha256: |
| 253 |
if digest == sha256: |
| 254 |
log("Verified sha256 integrity of %s" % url) |
| 255 |
else: |
| 256 |
raise IntegrityError( |
| 257 |
"sha256 mismatch on %s: wanted %s; got %s" % (url, sha256, digest) |
| 258 |
) |
| 259 |
|
| 260 |
|
| 261 |
def download_to_path(url, path, sha256=None, size=None, headers=None): |
| 262 |
"""Download a URL to a filesystem path, possibly with verification.""" |
| 263 |
|
| 264 |
# We download to a temporary file and rename at the end so there's |
| 265 |
# no chance of the final file being partially written or containing |
| 266 |
# bad data. |
| 267 |
try: |
| 268 |
path.unlink() |
| 269 |
except FileNotFoundError: |
| 270 |
pass |
| 271 |
|
| 272 |
for _ in retrier(attempts=5, sleeptime=60): |
| 273 |
try: |
| 274 |
log("Downloading %s to %s" % (url, path)) |
| 275 |
|
| 276 |
with rename_after_close(path, "wb") as fh: |
| 277 |
for chunk in stream_download( |
| 278 |
url, sha256=sha256, size=size, headers=headers |
| 279 |
): |
| 280 |
fh.write(chunk) |
| 281 |
|
| 282 |
return |
| 283 |
except Exception as e: |
| 284 |
log("Download failed: {}".format(e)) |
| 285 |
continue |
| 286 |
|
| 287 |
raise Exception("Download failed, no more retries!") |
| 288 |
|
| 289 |
|
| 290 |
def download_to_memory(url, sha256=None, size=None): |
| 291 |
"""Download a URL to memory, possibly with verification.""" |
| 292 |
|
| 293 |
for _ in retrier(attempts=5, sleeptime=60): |
| 294 |
data = b"" |
| 295 |
log("Downloading %s" % (url)) |
| 296 |
|
| 297 |
try: |
| 298 |
for chunk in stream_download(url, sha256=sha256, size=size): |
| 299 |
data += chunk |
| 300 |
|
| 301 |
return data |
| 302 |
except Exception as e: |
| 303 |
log("Download failed: {}".format(e)) |
| 304 |
continue |
| 305 |
|
| 306 |
raise Exception("Download failed, no more retries!") |
| 307 |
|
| 308 |
|
| 309 |
def gpg_verify_path(path: pathlib.Path, public_key_data: bytes, signature_data: bytes): |
| 310 |
"""Verify that a filesystem path verifies using GPG. |
| 311 |
|
| 312 |
Takes a Path defining a file to verify. ``public_key_data`` contains |
| 313 |
bytes with GPG public key data. ``signature_data`` contains a signed |
| 314 |
GPG document to use with ``gpg --verify``. |
| 315 |
""" |
| 316 |
log("Validating GPG signature of %s" % path) |
| 317 |
log("GPG key data:\n%s" % public_key_data.decode("ascii")) |
| 318 |
|
| 319 |
with tempfile.TemporaryDirectory() as td: |
| 320 |
try: |
| 321 |
# --batch since we're running unattended. |
| 322 |
gpg_args = ["gpg", "--homedir", td, "--batch"] |
| 323 |
|
| 324 |
log("Importing GPG key...") |
| 325 |
subprocess.run(gpg_args + ["--import"], input=public_key_data, check=True) |
| 326 |
|
| 327 |
log("Verifying GPG signature...") |
| 328 |
subprocess.run( |
| 329 |
gpg_args + ["--verify", "-", "%s" % path], |
| 330 |
input=signature_data, |
| 331 |
check=True, |
| 332 |
) |
| 333 |
|
| 334 |
log("GPG signature verified!") |
| 335 |
finally: |
| 336 |
# There is a race between the agent self-terminating and |
| 337 |
# shutil.rmtree() from the temporary directory cleanup that can |
| 338 |
# lead to exceptions. Kill the agent before cleanup to prevent this. |
| 339 |
env = dict(os.environ) |
| 340 |
env["GNUPGHOME"] = td |
| 341 |
subprocess.run(["gpgconf", "--kill", "gpg-agent"], env=env) |
| 342 |
|
| 343 |
|
| 344 |
class ArchiveTypeNotSupported(Exception): |
| 345 |
def __init__(self, path: pathlib.Path): |
| 346 |
super(Exception, self).__init__("Archive type not supported for %s" % path) |
| 347 |
|
| 348 |
|
| 349 |
def open_stream(path: pathlib.Path): |
| 350 |
"""Attempt to identify a path as an extractable archive by looking at its |
| 351 |
content.""" |
| 352 |
fh = path.open(mode="rb") |
| 353 |
magic = fh.read(6) |
| 354 |
fh.seek(0) |
| 355 |
if magic[:2] == b"PK": |
| 356 |
return "zip", fh |
| 357 |
if magic[:2] == b"\x1f\x8b": |
| 358 |
fh = gzip.GzipFile(fileobj=fh) |
| 359 |
elif magic[:3] == b"BZh": |
| 360 |
fh = bz2.BZ2File(fh) |
| 361 |
elif magic == b"\xfd7zXZ\x00": |
| 362 |
fh = lzma.LZMAFile(fh) |
| 363 |
elif magic[:4] == b"\x28\xb5\x2f\xfd": |
| 364 |
fh = ZstdDecompressor().stream_reader(fh) |
| 365 |
fh = io.BufferedReader(fh) |
| 366 |
try: |
| 367 |
# A full tar info header is 512 bytes. |
| 368 |
headers = fh.peek(512) |
| 369 |
# 257 is the offset of the ustar magic. |
| 370 |
magic = headers[257 : 257 + 8] |
| 371 |
# For older unix tar, rely on TarInfo.frombuf's checksum check |
| 372 |
if magic in (b"ustar\x0000", b"ustar \x00") or tarfile.TarInfo.frombuf( |
| 373 |
headers[:512], tarfile.ENCODING, "surrogateescape" |
| 374 |
): |
| 375 |
return "tar", fh |
| 376 |
except Exception as e: |
| 377 |
pass |
| 378 |
raise ArchiveTypeNotSupported(path) |
| 379 |
|
| 380 |
|
| 381 |
def archive_type(path: pathlib.Path): |
| 382 |
"""Attempt to identify a path as an extractable archive.""" |
| 383 |
if path.suffixes[-2:-1] == [".tar"] or path.suffixes[-1:] == [".tgz"]: |
| 384 |
return "tar" |
| 385 |
elif path.suffix == ".zip": |
| 386 |
return "zip" |
| 387 |
else: |
| 388 |
return None |
| 389 |
|
| 390 |
|
| 391 |
def extract_archive(path, dest_dir): |
| 392 |
"""Extract an archive to a destination directory.""" |
| 393 |
|
| 394 |
# Resolve paths to absolute variants. |
| 395 |
path = path.resolve() |
| 396 |
dest_dir = dest_dir.resolve() |
| 397 |
|
| 398 |
log("Extracting %s to %s" % (path, dest_dir)) |
| 399 |
t0 = time.time() |
| 400 |
|
| 401 |
# We pipe input to the decompressor program so that we can apply |
| 402 |
# custom decompressors that the program may not know about. |
| 403 |
typ, ifh = open_stream(path) |
| 404 |
if typ == "tar": |
| 405 |
# On Windows, the tar program doesn't support things like symbolic |
| 406 |
# links, while Windows actually support them. The tarfile module in |
| 407 |
# python does. So use that. But since it's significantly slower than |
| 408 |
# the tar program on Linux, only use tarfile on Windows (tarfile is |
| 409 |
# also not much slower on Windows, presumably because of the |
| 410 |
# notoriously bad I/O). |
| 411 |
if sys.platform == "win32": |
| 412 |
tar = tarfile.open(fileobj=ifh, mode="r|") |
| 413 |
tar.extractall(str(dest_dir)) |
| 414 |
args = [] |
| 415 |
else: |
| 416 |
args = ["tar", "xf", "-"] |
| 417 |
pipe_stdin = True |
| 418 |
elif typ == "zip": |
| 419 |
# unzip from stdin has wonky behavior. We don't use a pipe for it. |
| 420 |
ifh = open(os.devnull, "rb") |
| 421 |
args = ["unzip", "-q", "-o", str(path)] |
| 422 |
pipe_stdin = False |
| 423 |
else: |
| 424 |
raise ValueError("unknown archive format: %s" % path) |
| 425 |
|
| 426 |
if args: |
| 427 |
with ifh, subprocess.Popen( |
| 428 |
args, cwd=str(dest_dir), bufsize=0, stdin=subprocess.PIPE |
| 429 |
) as p: |
| 430 |
while True: |
| 431 |
if not pipe_stdin: |
| 432 |
break |
| 433 |
|
| 434 |
chunk = ifh.read(131072) |
| 435 |
if not chunk: |
| 436 |
break |
| 437 |
|
| 438 |
p.stdin.write(chunk) |
| 439 |
|
| 440 |
if p.returncode: |
| 441 |
raise Exception("%r exited %d" % (args, p.returncode)) |
| 442 |
|
| 443 |
log("%s extracted in %.3fs" % (path, time.time() - t0)) |
| 444 |
|
| 445 |
|
| 446 |
def should_repack_archive( |
| 447 |
orig: pathlib.Path, dest: pathlib.Path, strip_components=0, add_prefix="" |
| 448 |
) -> bool: |
| 449 |
""" |
| 450 |
Determines whether we should attempt to repack an archive based on the naming conventions used |
| 451 |
in the original file path, the destination file path, and any modifications such as stripping |
| 452 |
components or adding a prefix. |
| 453 |
""" |
| 454 |
|
| 455 |
if strip_components or add_prefix: |
| 456 |
# If strip_components or add_prefix is specified, we should always repack. |
| 457 |
return True |
| 458 |
|
| 459 |
if orig.suffixes == dest.suffixes: |
| 460 |
# If all suffixes are exactly the same, then a rename will suffice. |
| 461 |
return False |
| 462 |
|
| 463 |
if dest.suffixes[-2:] == [".tar", ".zst"]: |
| 464 |
# If the destination is a ".tar.zst" file then we will always try to repack it ourselves. |
| 465 |
return True |
| 466 |
|
| 467 |
if orig.suffix == dest.suffix: |
| 468 |
# If the final suffix is the same, this is likely just a rename. |
| 469 |
# |
| 470 |
# This may be a case where multiple suffixes were detected unnecessarily due to the file name |
| 471 |
# containing a semantic version. For example the file "python-3.8.10-amd64.exe" would be detected |
| 472 |
# to have three suffixes [".8", ".10-amd64", ".exe"]. Changing this to "python.exe" should be a |
| 473 |
# simple rename, rather than a repack. |
| 474 |
# |
| 475 |
# In this case, we will try to determine if the original path has a supported archive suffix. |
| 476 |
# If the original path is detected to be an archive, we will try to repack, otherwise rename. |
| 477 |
return archive_type(orig) is not None |
| 478 |
|
| 479 |
# Otherwise, if the paths aren't the same, assume it's an archive and try to repack. |
| 480 |
# |
| 481 |
# It would be best to fail early if the repack fails than to fail during a test because a renamed |
| 482 |
# file was incorrect type after all. |
| 483 |
return True |
| 484 |
|
| 485 |
|
| 486 |
EXECUTABLE_SIGNATURES = set([ |
| 487 |
b"\xFE\xED\xFA\xCE", # mach-o 32-bits big endian |
| 488 |
b"\xCE\xFA\xED\xFE", # mach-o 32-bits little endian |
| 489 |
b"\xFE\xED\xFA\xCF", # mach-o 64-bits big endian |
| 490 |
b"\xCF\xFA\xED\xFE", # mach-o 64-bits little endian |
| 491 |
b"\xCA\xFE\xBA\xBE", # mach-o FAT binary |
| 492 |
b"\x7F\x45\x4C\x46", # Elf binary |
| 493 |
]) |
| 494 |
|
| 495 |
|
| 496 |
def repack_archive( |
| 497 |
orig: pathlib.Path, |
| 498 |
dest: pathlib.Path, |
| 499 |
strip_components=0, |
| 500 |
prefix="", |
| 501 |
force_archive=False, |
| 502 |
): |
| 503 |
assert orig != dest |
| 504 |
log(f"Repacking {orig} as {dest}") |
| 505 |
try: |
| 506 |
orig_typ, ifh = open_stream(orig) |
| 507 |
except ArchiveTypeNotSupported: |
| 508 |
if force_archive: |
| 509 |
ifh = io.BufferedReader(orig.open(mode="rb")) |
| 510 |
signature = ifh.peek(4)[:4] |
| 511 |
orig_typ = "exec" if signature in EXECUTABLE_SIGNATURES else None |
| 512 |
else: |
| 513 |
raise |
| 514 |
typ = archive_type(dest) |
| 515 |
if not typ: |
| 516 |
raise Exception("Archive type not supported for %s" % dest.name) |
| 517 |
|
| 518 |
if dest.suffixes[-2:] != [".tar", ".zst"]: |
| 519 |
raise Exception("Only producing .tar.zst archives is supported.") |
| 520 |
|
| 521 |
if strip_components or prefix: |
| 522 |
|
| 523 |
def filter(name): |
| 524 |
if strip_components: |
| 525 |
stripped = "/".join(name.split("/")[strip_components:]) |
| 526 |
if not stripped: |
| 527 |
raise Exception( |
| 528 |
"Stripping %d components would remove files" % strip_components |
| 529 |
) |
| 530 |
name = stripped |
| 531 |
return prefix + name |
| 532 |
|
| 533 |
else: |
| 534 |
filter = None |
| 535 |
|
| 536 |
with rename_after_close(dest, "wb") as fh: |
| 537 |
ctx = ZstdCompressor() |
| 538 |
if orig_typ in ("exec", None): |
| 539 |
with ctx.stream_writer(fh) as compressor, tarfile.open( |
| 540 |
fileobj=compressor, |
| 541 |
mode="w:", |
| 542 |
) as tar: |
| 543 |
tarinfo = tarfile.TarInfo() |
| 544 |
tarinfo.name = filter(orig.name) if filter else orig.name |
| 545 |
st = orig.stat() |
| 546 |
tarinfo.size = st.st_size |
| 547 |
tarinfo.mtime = st.st_mtime |
| 548 |
tarinfo.mode = 0o0755 if orig_typ == "exec" else 0o0644 |
| 549 |
tar.addfile(tarinfo, ifh) |
| 550 |
|
| 551 |
elif orig_typ == "zip": |
| 552 |
assert typ == "tar" |
| 553 |
zip = zipfile.ZipFile(ifh) |
| 554 |
# Convert the zip stream to a tar on the fly. |
| 555 |
with ctx.stream_writer(fh) as compressor, tarfile.open( |
| 556 |
fileobj=compressor, mode="w:" |
| 557 |
) as tar: |
| 558 |
for zipinfo in zip.infolist(): |
| 559 |
if zipinfo.is_dir(): |
| 560 |
continue |
| 561 |
tarinfo = tarfile.TarInfo() |
| 562 |
filename = zipinfo.filename |
| 563 |
tarinfo.name = filter(filename) if filter else filename |
| 564 |
tarinfo.size = zipinfo.file_size |
| 565 |
# Zip files don't have any knowledge of the timezone |
| 566 |
# they were created in. Which is not really convenient to |
| 567 |
# reliably convert to a timestamp. But we don't really |
| 568 |
# care about accuracy, but rather about reproducibility, |
| 569 |
# so we pick UTC. |
| 570 |
time = datetime.datetime( |
| 571 |
*zipinfo.date_time, tzinfo=datetime.timezone.utc |
| 572 |
) |
| 573 |
tarinfo.mtime = time.timestamp() |
| 574 |
# 0 is MS-DOS, 3 is UNIX. Only in the latter case do we |
| 575 |
# get anything useful for the tar file mode. |
| 576 |
if zipinfo.create_system == 3: |
| 577 |
mode = zipinfo.external_attr >> 16 |
| 578 |
else: |
| 579 |
mode = 0o0644 |
| 580 |
tarinfo.mode = stat.S_IMODE(mode) |
| 581 |
if stat.S_ISLNK(mode): |
| 582 |
tarinfo.type = tarfile.SYMTYPE |
| 583 |
tarinfo.linkname = zip.read(filename).decode() |
| 584 |
tar.addfile(tarinfo, zip.open(filename)) |
| 585 |
elif stat.S_ISREG(mode) or stat.S_IFMT(mode) == 0: |
| 586 |
tar.addfile(tarinfo, zip.open(filename)) |
| 587 |
else: |
| 588 |
raise Exception("Unsupported file mode %o" % stat.S_IFMT(mode)) |
| 589 |
|
| 590 |
elif orig_typ == "tar": |
| 591 |
if typ == "zip": |
| 592 |
raise Exception("Repacking a tar to zip is not supported") |
| 593 |
assert typ == "tar" |
| 594 |
|
| 595 |
if filter: |
| 596 |
# To apply the filter, we need to open the tar stream and |
| 597 |
# tweak it. |
| 598 |
origtar = tarfile.open(fileobj=ifh, mode="r|") |
| 599 |
with ctx.stream_writer(fh) as compressor, tarfile.open( |
| 600 |
fileobj=compressor, |
| 601 |
mode="w:", |
| 602 |
format=origtar.format, |
| 603 |
) as tar: |
| 604 |
for tarinfo in origtar: |
| 605 |
if tarinfo.isdir(): |
| 606 |
continue |
| 607 |
tarinfo.name = filter(tarinfo.name) |
| 608 |
if "path" in tarinfo.pax_headers: |
| 609 |
tarinfo.pax_headers["path"] = filter( |
| 610 |
tarinfo.pax_headers["path"] |
| 611 |
) |
| 612 |
if tarinfo.isfile(): |
| 613 |
tar.addfile(tarinfo, origtar.extractfile(tarinfo)) |
| 614 |
else: |
| 615 |
tar.addfile(tarinfo) |
| 616 |
else: |
| 617 |
# We only change compression here. The tar stream is unchanged. |
| 618 |
ctx.copy_stream(ifh, fh) |
| 619 |
|
| 620 |
else: |
| 621 |
raise Exception( |
| 622 |
f"Attempt to repack an archive of unsupported type {orig_typ}" |
| 623 |
) |
| 624 |
|
| 625 |
|
| 626 |
def fetch_and_extract(url, dest_dir, extract=True, sha256=None, size=None): |
| 627 |
"""Fetch a URL and extract it to a destination path. |
| 628 |
|
| 629 |
If the downloaded URL is an archive, it is extracted automatically |
| 630 |
and the archive is deleted. Otherwise the file remains in place in |
| 631 |
the destination directory. |
| 632 |
""" |
| 633 |
|
| 634 |
basename = urllib.parse.urlparse(url).path.split("/")[-1] |
| 635 |
dest_path = dest_dir / basename |
| 636 |
|
| 637 |
download_to_path(url, dest_path, sha256=sha256, size=size) |
| 638 |
|
| 639 |
if not extract: |
| 640 |
return |
| 641 |
|
| 642 |
try: |
| 643 |
extract_archive(dest_path, dest_dir) |
| 644 |
log("Removing %s" % dest_path) |
| 645 |
dest_path.unlink() |
| 646 |
except ArchiveTypeNotSupported: |
| 647 |
pass |
| 648 |
|
| 649 |
|
| 650 |
def fetch_urls(downloads): |
| 651 |
"""Fetch URLs pairs to a pathlib.Path.""" |
| 652 |
with concurrent.futures.ThreadPoolExecutor(CONCURRENCY) as e: |
| 653 |
fs = [] |
| 654 |
|
| 655 |
for download in downloads: |
| 656 |
fs.append(e.submit(fetch_and_extract, *download)) |
| 657 |
|
| 658 |
for f in fs: |
| 659 |
f.result() |
| 660 |
|
| 661 |
|
| 662 |
def _git_checkout_github_archive( |
| 663 |
dest_path: pathlib.Path, repo: str, commit: str, prefix: str |
| 664 |
): |
| 665 |
"Use github archive generator to speed up github git repo cloning" |
| 666 |
repo = repo.rstrip("/") |
| 667 |
github_url = "{repo}/archive/{commit}.tar.gz".format(**locals()) |
| 668 |
|
| 669 |
with tempfile.TemporaryDirectory() as td: |
| 670 |
temp_dir = pathlib.Path(td) |
| 671 |
dl_dest = temp_dir / "archive.tar.gz" |
| 672 |
download_to_path(github_url, dl_dest) |
| 673 |
repack_archive(dl_dest, dest_path, strip_components=1, prefix=prefix + "/") |
| 674 |
|
| 675 |
|
| 676 |
def _github_submodule_required(repo: str, commit: str): |
| 677 |
"Use github API to check if submodules are used" |
| 678 |
url = "{repo}/blob/{commit}/.gitmodules".format(**locals()) |
| 679 |
try: |
| 680 |
status_code = urllib.request.urlopen(url).getcode() |
| 681 |
return status_code == 200 |
| 682 |
except: |
| 683 |
return False |
| 684 |
|
| 685 |
|
| 686 |
def git_checkout_archive( |
| 687 |
dest_path: pathlib.Path, |
| 688 |
repo: str, |
| 689 |
commit: str, |
| 690 |
prefix=None, |
| 691 |
ssh_key=None, |
| 692 |
include_dot_git=False, |
| 693 |
): |
| 694 |
"""Produce an archive of the files comprising a Git checkout.""" |
| 695 |
dest_path.parent.mkdir(parents=True, exist_ok=True) |
| 696 |
|
| 697 |
if not prefix: |
| 698 |
prefix = repo.rstrip("/").rsplit("/", 1)[-1] |
| 699 |
|
| 700 |
if dest_path.suffixes[-2:] != [".tar", ".zst"]: |
| 701 |
raise Exception("Only producing .tar.zst archives is supported.") |
| 702 |
|
| 703 |
if repo.startswith("https://github.com/"): |
| 704 |
if not include_dot_git and not _github_submodule_required(repo, commit): |
| 705 |
log("Using github archive service to speedup archive creation") |
| 706 |
# Always log sha1 info, either from commit or resolved from repo. |
| 707 |
if re.match(r"^[a-fA-F0-9]{40}$", commit): |
| 708 |
revision = commit |
| 709 |
else: |
| 710 |
ref_output = subprocess.check_output( |
| 711 |
["git", "ls-remote", repo, "refs/heads/" + commit] |
| 712 |
) |
| 713 |
revision, _ = ref_output.decode().split(maxsplit=1) |
| 714 |
log("Fetching revision {}".format(revision)) |
| 715 |
return _git_checkout_github_archive(dest_path, repo, commit, prefix) |
| 716 |
|
| 717 |
with tempfile.TemporaryDirectory() as td: |
| 718 |
temp_dir = pathlib.Path(td) |
| 719 |
|
| 720 |
git_dir = temp_dir / prefix |
| 721 |
|
| 722 |
# This could be faster with a shallow clone. However, Git requires a ref |
| 723 |
# to initiate a clone. Since the commit-ish may not refer to a ref, we |
| 724 |
# simply perform a full clone followed by a checkout. |
| 725 |
print("cloning %s to %s" % (repo, git_dir)) |
| 726 |
|
| 727 |
env = os.environ.copy() |
| 728 |
keypath = "" |
| 729 |
if ssh_key: |
| 730 |
taskcluster_secret_url = api( |
| 731 |
os.environ.get("TASKCLUSTER_PROXY_URL"), |
| 732 |
"secrets", |
| 733 |
"v1", |
| 734 |
"secret/{keypath}".format(keypath=ssh_key), |
| 735 |
) |
| 736 |
taskcluster_secret = b"".join(stream_download(taskcluster_secret_url)) |
| 737 |
taskcluster_secret = json.loads(taskcluster_secret) |
| 738 |
sshkey = taskcluster_secret["secret"]["ssh_privkey"] |
| 739 |
|
| 740 |
keypath = temp_dir.joinpath("ssh-key") |
| 741 |
keypath.write_text(sshkey) |
| 742 |
keypath.chmod(0o600) |
| 743 |
|
| 744 |
env = { |
| 745 |
"GIT_SSH_COMMAND": "ssh -o 'StrictHostKeyChecking no' -i {keypath}".format( |
| 746 |
keypath=keypath |
| 747 |
) |
| 748 |
} |
| 749 |
|
| 750 |
subprocess.run(["git", "clone", "-n", repo, str(git_dir)], check=True, env=env) |
| 751 |
|
| 752 |
# Always use a detached head so that git prints out what it checked out. |
| 753 |
subprocess.run( |
| 754 |
["git", "checkout", "--detach", commit], cwd=str(git_dir), check=True |
| 755 |
) |
| 756 |
|
| 757 |
# When including the .git, we want --depth 1, but a direct clone would not |
| 758 |
# necessarily be able to give us the right commit. |
| 759 |
if include_dot_git: |
| 760 |
initial_clone = git_dir.with_name(git_dir.name + ".orig") |
| 761 |
git_dir.rename(initial_clone) |
| 762 |
subprocess.run( |
| 763 |
[ |
| 764 |
"git", |
| 765 |
"clone", |
| 766 |
"file://" + str(initial_clone), |
| 767 |
str(git_dir), |
| 768 |
"--depth", |
| 769 |
"1", |
| 770 |
], |
| 771 |
check=True, |
| 772 |
) |
| 773 |
subprocess.run( |
| 774 |
["git", "remote", "set-url", "origin", repo], |
| 775 |
cwd=str(git_dir), |
| 776 |
check=True, |
| 777 |
) |
| 778 |
|
| 779 |
# --depth 1 can induce more work on the server side, so only use it for |
| 780 |
# submodule initialization when we want to keep the .git directory. |
| 781 |
depth = ["--depth", "1"] if include_dot_git else [] |
| 782 |
subprocess.run( |
| 783 |
["git", "submodule", "update", "--init"] + depth, |
| 784 |
cwd=str(git_dir), |
| 785 |
check=True, |
| 786 |
) |
| 787 |
|
| 788 |
if keypath: |
| 789 |
os.remove(keypath) |
| 790 |
|
| 791 |
print("creating archive %s of commit %s" % (dest_path, commit)) |
| 792 |
exclude_dot_git = [] if include_dot_git else ["--exclude=.git"] |
| 793 |
proc = subprocess.Popen( |
| 794 |
[ |
| 795 |
"tar", |
| 796 |
"cf", |
| 797 |
"-", |
| 798 |
] |
| 799 |
+ exclude_dot_git |
| 800 |
+ [ |
| 801 |
"-C", |
| 802 |
str(temp_dir), |
| 803 |
prefix, |
| 804 |
], |
| 805 |
stdout=subprocess.PIPE, |
| 806 |
) |
| 807 |
|
| 808 |
with rename_after_close(dest_path, "wb") as out: |
| 809 |
ctx = ZstdCompressor() |
| 810 |
ctx.copy_stream(proc.stdout, out) |
| 811 |
|
| 812 |
proc.wait() |
| 813 |
|
| 814 |
|
| 815 |
def command_git_checkout_archive(args): |
| 816 |
dest = pathlib.Path(args.dest) |
| 817 |
|
| 818 |
try: |
| 819 |
git_checkout_archive( |
| 820 |
dest, |
| 821 |
args.repo, |
| 822 |
args.commit, |
| 823 |
prefix=args.path_prefix, |
| 824 |
ssh_key=args.ssh_key_secret, |
| 825 |
include_dot_git=args.include_dot_git, |
| 826 |
) |
| 827 |
except Exception: |
| 828 |
try: |
| 829 |
dest.unlink() |
| 830 |
except FileNotFoundError: |
| 831 |
pass |
| 832 |
|
| 833 |
raise |
| 834 |
|
| 835 |
|
| 836 |
def command_static_url(args): |
| 837 |
gpg_sig_url = args.gpg_sig_url |
| 838 |
gpg_env_key = args.gpg_key_env |
| 839 |
|
| 840 |
if bool(gpg_sig_url) != bool(gpg_env_key): |
| 841 |
print("--gpg-sig-url and --gpg-key-env must both be defined") |
| 842 |
return 1 |
| 843 |
|
| 844 |
if gpg_sig_url: |
| 845 |
gpg_signature = b"".join(stream_download(gpg_sig_url)) |
| 846 |
gpg_key = os.environb[gpg_env_key.encode("ascii")] |
| 847 |
|
| 848 |
dest = pathlib.Path(args.dest) |
| 849 |
dest.parent.mkdir(parents=True, exist_ok=True) |
| 850 |
|
| 851 |
basename = urllib.parse.urlparse(args.url).path.split("/")[-1] |
| 852 |
if basename.endswith("".join(dest.suffixes)): |
| 853 |
dl_dest = dest |
| 854 |
else: |
| 855 |
dl_dest = dest.parent / basename |
| 856 |
|
| 857 |
try: |
| 858 |
download_to_path( |
| 859 |
args.url, dl_dest, sha256=args.sha256, size=args.size, headers=args.headers |
| 860 |
) |
| 861 |
|
| 862 |
if gpg_sig_url: |
| 863 |
gpg_verify_path(dl_dest, gpg_key, gpg_signature) |
| 864 |
|
| 865 |
if args.force_archive or should_repack_archive( |
| 866 |
dl_dest, dest, args.strip_components, args.add_prefix |
| 867 |
): |
| 868 |
repack_archive( |
| 869 |
dl_dest, dest, args.strip_components, args.add_prefix, args.force_archive |
| 870 |
) |
| 871 |
elif dl_dest != dest: |
| 872 |
log(f"Renaming {dl_dest} to {dest}") |
| 873 |
dl_dest.rename(dest) |
| 874 |
|
| 875 |
except Exception: |
| 876 |
try: |
| 877 |
dl_dest.unlink() |
| 878 |
except FileNotFoundError: |
| 879 |
pass |
| 880 |
|
| 881 |
raise |
| 882 |
|
| 883 |
if dl_dest != dest and dl_dest.exists(): |
| 884 |
log("Removing %s" % dl_dest) |
| 885 |
dl_dest.unlink() |
| 886 |
|
| 887 |
|
| 888 |
def api(root_url, service, version, path): |
| 889 |
# taskcluster-lib-urls is not available when this script runs, so |
| 890 |
# simulate its behavior: |
| 891 |
return "{root_url}/api/{service}/{version}/{path}".format( |
| 892 |
root_url=root_url, service=service, version=version, path=path |
| 893 |
) |
| 894 |
|
| 895 |
|
| 896 |
def get_hash(fetch, root_url): |
| 897 |
path = "task/{task}/artifacts/{artifact}".format( |
| 898 |
task=fetch["task"], artifact="public/chain-of-trust.json" |
| 899 |
) |
| 900 |
url = api(root_url, "queue", "v1", path) |
| 901 |
cot = json.loads(download_to_memory(url)) |
| 902 |
return cot["artifacts"][fetch["artifact"]]["sha256"] |
| 903 |
|
| 904 |
|
| 905 |
def command_task_artifacts(args): |
| 906 |
start = time.monotonic() |
| 907 |
fetches = json.loads(os.environ["MOZ_FETCHES"]) |
| 908 |
downloads = [] |
| 909 |
for fetch in fetches: |
| 910 |
extdir = pathlib.Path(args.dest) |
| 911 |
if "dest" in fetch: |
| 912 |
# Note: normpath doesn't like pathlib.Path in python 3.5 |
| 913 |
extdir = pathlib.Path(os.path.normpath(str(extdir.joinpath(fetch["dest"])))) |
| 914 |
extdir.mkdir(parents=True, exist_ok=True) |
| 915 |
root_url = os.environ["TASKCLUSTER_ROOT_URL"] |
| 916 |
sha256 = None |
| 917 |
if fetch.get("verify-hash"): |
| 918 |
sha256 = get_hash(fetch, root_url) |
| 919 |
if fetch["artifact"].startswith("public/"): |
| 920 |
path = "task/{task}/artifacts/{artifact}".format( |
| 921 |
task=fetch["task"], artifact=fetch["artifact"] |
| 922 |
) |
| 923 |
url = api(root_url, "queue", "v1", path) |
| 924 |
else: |
| 925 |
url = ("{proxy_url}/api/queue/v1/task/{task}/artifacts/{artifact}").format( |
| 926 |
proxy_url=os.environ["TASKCLUSTER_PROXY_URL"], |
| 927 |
task=fetch["task"], |
| 928 |
artifact=fetch["artifact"], |
| 929 |
) |
| 930 |
downloads.append((url, extdir, fetch["extract"], sha256)) |
| 931 |
|
| 932 |
fetch_urls(downloads) |
| 933 |
end = time.monotonic() |
| 934 |
|
| 935 |
perfherder_data = { |
| 936 |
"framework": {"name": "build_metrics"}, |
| 937 |
"suites": [ |
| 938 |
{ |
| 939 |
"name": "fetch_content", |
| 940 |
"value": end - start, |
| 941 |
"lowerIsBetter": True, |
| 942 |
"shouldAlert": False, |
| 943 |
"subtests": [], |
| 944 |
} |
| 945 |
], |
| 946 |
} |
| 947 |
print("PERFHERDER_DATA: {}".format(json.dumps(perfherder_data)), file=sys.stderr) |
| 948 |
|
| 949 |
|
| 950 |
def main(): |
| 951 |
parser = argparse.ArgumentParser() |
| 952 |
subparsers = parser.add_subparsers(title="sub commands") |
| 953 |
|
| 954 |
git_checkout = subparsers.add_parser( |
| 955 |
"git-checkout-archive", |
| 956 |
help="Obtain an archive of files from a Git repository checkout", |
| 957 |
) |
| 958 |
git_checkout.set_defaults(func=command_git_checkout_archive) |
| 959 |
git_checkout.add_argument( |
| 960 |
"--path-prefix", help="Prefix for paths in produced archive" |
| 961 |
) |
| 962 |
git_checkout.add_argument("repo", help="URL to Git repository to be cloned") |
| 963 |
git_checkout.add_argument("commit", help="Git commit to check out") |
| 964 |
git_checkout.add_argument("dest", help="Destination path of archive") |
| 965 |
git_checkout.add_argument( |
| 966 |
"--ssh-key-secret", help="The scope path of the ssh key to used for checkout" |
| 967 |
) |
| 968 |
git_checkout.add_argument( |
| 969 |
"--include-dot-git", action="store_true", help="Include the .git directory" |
| 970 |
) |
| 971 |
|
| 972 |
url = subparsers.add_parser("static-url", help="Download a static URL") |
| 973 |
url.set_defaults(func=command_static_url) |
| 974 |
url.add_argument("--sha256", required=True, help="SHA-256 of downloaded content") |
| 975 |
url.add_argument( |
| 976 |
"--size", required=True, type=int, help="Size of downloaded content, in bytes" |
| 977 |
) |
| 978 |
url.add_argument( |
| 979 |
"--gpg-sig-url", |
| 980 |
help="URL containing signed GPG document validating " "URL to fetch", |
| 981 |
) |
| 982 |
url.add_argument( |
| 983 |
"--gpg-key-env", help="Environment variable containing GPG key to validate" |
| 984 |
) |
| 985 |
url.add_argument( |
| 986 |
"--strip-components", |
| 987 |
type=int, |
| 988 |
default=0, |
| 989 |
help="Number of leading components to strip from file " |
| 990 |
"names in the downloaded archive", |
| 991 |
) |
| 992 |
url.add_argument( |
| 993 |
"--add-prefix", |
| 994 |
default="", |
| 995 |
help="Prefix to add to file names in the downloaded " "archive", |
| 996 |
) |
| 997 |
url.add_argument( |
| 998 |
"-H", |
| 999 |
"--header", |
| 1000 |
default=[], |
| 1001 |
action="append", |
| 1002 |
dest="headers", |
| 1003 |
help="Header to send as part of the request, can be passed " "multiple times", |
| 1004 |
) |
| 1005 |
url.add_argument( |
| 1006 |
"--force-archive", |
| 1007 |
action="store_true", |
| 1008 |
help="Create an archive even when the downloaded file is not an archive", |
| 1009 |
) |
| 1010 |
url.add_argument("url", help="URL to fetch") |
| 1011 |
url.add_argument("dest", help="Destination path") |
| 1012 |
|
| 1013 |
artifacts = subparsers.add_parser("task-artifacts", help="Fetch task artifacts") |
| 1014 |
artifacts.set_defaults(func=command_task_artifacts) |
| 1015 |
artifacts.add_argument( |
| 1016 |
"-d", |
| 1017 |
"--dest", |
| 1018 |
default=os.environ.get("MOZ_FETCHES_DIR"), |
| 1019 |
help="Destination directory which will contain all " |
| 1020 |
"artifacts (defaults to $MOZ_FETCHES_DIR)", |
| 1021 |
) |
| 1022 |
|
| 1023 |
args = parser.parse_args() |
| 1024 |
|
| 1025 |
if not args.dest: |
| 1026 |
parser.error( |
| 1027 |
"no destination directory specified, either pass in --dest " |
| 1028 |
"or set $MOZ_FETCHES_DIR" |
| 1029 |
) |
| 1030 |
|
| 1031 |
return args.func(args) |
| 1032 |
|
| 1033 |
|
| 1034 |
if __name__ == "__main__": |
| 1035 |
sys.exit(main()) |