| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426 |
- #!/usr/bin/env python3
- """Resumable, hash-verified artifact upload/download over the existing LAN SSH.
- Both Windows transfer adapters forward here. Source synchronization remains Git.
- Only verified chunks are reused; final files appear after whole-file verification.
- """
- from __future__ import annotations
- import argparse
- import base64
- from contextlib import contextmanager
- import hashlib
- import json
- import os
- from pathlib import Path
- import re
- import shlex
- import subprocess
- import sys
- import time
- REMOTE_ROOT = Path("/data/prod2u")
- MIN_CHUNK = 65536
- MAX_CHUNK = 256 * 1024 * 1024
- DEFAULT_CHUNK = 4 * 1024 * 1024
- BLOCK = 1024 * 1024
- class TransferError(RuntimeError):
- def __init__(self, message, code=2):
- super().__init__(message)
- self.code = code
- def file_sha(path):
- with Path(path).open("rb") as stream:
- return hashlib.file_digest(stream, "sha256").hexdigest()
- def valid_sha(value):
- if not isinstance(value, str) or not re.fullmatch("[0-9a-f]{64}", value):
- raise ValueError("expected a lowercase SHA256 digest")
- def validate_manifest(manifest):
- valid_sha(manifest["sha256"])
- size, chunk_bytes = manifest["size"], manifest["chunk_bytes"]
- if not isinstance(size, int) or size < 0 or not MIN_CHUNK <= chunk_bytes <= MAX_CHUNK:
- raise ValueError("invalid file size or chunk size (64 KiB..256 MiB)")
- offset = 0
- for index, chunk in enumerate(manifest["chunks"]):
- valid_sha(chunk["sha256"])
- if (chunk["index"] != index or chunk["offset"] != offset
- or chunk["size"] != min(chunk_bytes, size - offset) or chunk["size"] <= 0):
- raise ValueError("invalid chunk index, size or offset")
- offset += chunk["size"]
- if offset != size:
- raise ValueError("chunk manifest does not cover the file")
- return manifest
- def describe(source, chunk_bytes=DEFAULT_CHUNK):
- if not MIN_CHUNK <= chunk_bytes <= MAX_CHUNK:
- raise ValueError("chunk size must be 64 KiB..256 MiB")
- source = Path(source)
- before = source.stat()
- whole = hashlib.sha256()
- chunks = []
- offset = 0
- with source.open("rb") as stream:
- while offset < before.st_size:
- length = min(chunk_bytes, before.st_size - offset)
- sha = hashlib.sha256()
- remaining = length
- while remaining:
- data = stream.read(min(BLOCK, remaining))
- if not data:
- raise TransferError("source changed while computing manifest")
- sha.update(data)
- whole.update(data)
- remaining -= len(data)
- chunks.append({"index": len(chunks), "offset": offset, "size": length, "sha256": sha.hexdigest()})
- offset += length
- if stream.read(1):
- raise TransferError("source grew while computing manifest")
- after = source.stat()
- if (before.st_size, before.st_mtime_ns, before.st_ino) != (after.st_size, after.st_mtime_ns, after.st_ino):
- raise TransferError("source changed while computing manifest")
- return validate_manifest({"schema": "prod2u-transfer-v1", "size": offset,
- "sha256": whole.hexdigest(), "chunk_bytes": chunk_bytes, "chunks": chunks})
- def matched(path, size, sha):
- path = Path(path)
- return path.is_file() and path.stat().st_size == size and file_sha(path) == sha
- def stage_path(destination, sha, chunk_bytes):
- identity = json.dumps([str(Path(destination).resolve()), sha, chunk_bytes], ensure_ascii=False).encode()
- return Path(destination).parent / ("transfer-parts-" + hashlib.sha256(identity).hexdigest()[:24])
- def part_path(stage, index):
- return stage / ("part-" + str(index).zfill(6))
- @contextmanager
- def destination_lock(destination):
- path = Path(str(destination) + ".transfer.lock")
- path.parent.mkdir(parents=True, exist_ok=True)
- with path.open("a+b") as stream:
- if sys.platform == "win32":
- import msvcrt
- stream.seek(0)
- if not stream.read(1):
- stream.write(b"0")
- stream.flush()
- stream.seek(0)
- msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1)
- try:
- yield
- finally:
- stream.seek(0)
- msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
- else:
- import fcntl
- fcntl.flock(stream, fcntl.LOCK_EX)
- yield
- def prepare_stage(destination, manifest):
- validate_manifest(manifest)
- stage = stage_path(destination, manifest["sha256"], manifest["chunk_bytes"])
- stage.mkdir(parents=True, exist_ok=True)
- path = stage / "MANIFEST.json"
- if path.exists():
- if json.loads(path.read_text(encoding="utf-8")) != manifest:
- raise TransferError("transfer staging manifest conflict")
- else:
- temporary = stage / "MANIFEST.json.partial"
- temporary.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
- temporary.replace(path)
- return stage
- def missing_parts(stage, manifest):
- return [chunk["index"] for chunk in manifest["chunks"]
- if not matched(part_path(stage, chunk["index"]), chunk["size"], chunk["sha256"])]
- def guard_destination(destination, size, sha, replace):
- if destination.exists():
- if matched(destination, size, sha):
- return True
- if not replace:
- raise TransferError("DESTINATION_CONFLICT: existing file differs; choose a new path or explicit --replace")
- return False
- def receive_part(stream, stage, chunk):
- final = part_path(stage, chunk["index"])
- partial = Path(str(final) + ".partial")
- sha = hashlib.sha256()
- remaining = chunk["size"]
- with partial.open("wb") as output:
- while remaining:
- data = stream.read(min(BLOCK, remaining))
- if not data:
- raise TransferError("INCOMPLETE_CHUNK: verified earlier chunks remain available", 3)
- output.write(data)
- sha.update(data)
- remaining -= len(data)
- if stream.read(1):
- raise TransferError("chunk contains extra bytes", 3)
- output.flush()
- os.fsync(output.fileno())
- if sha.hexdigest() != chunk["sha256"]:
- raise TransferError("CHUNK_HASH_MISMATCH: chunk was not committed", 3)
- partial.replace(final)
- def assemble(destination, manifest, stage, replace=False):
- if guard_destination(destination, manifest["size"], manifest["sha256"], replace):
- return
- missing = missing_parts(stage, manifest)
- if missing:
- raise TransferError("missing or corrupt chunks: " + ",".join(map(str, missing)))
- partial = Path(str(destination) + ".partial")
- whole = hashlib.sha256()
- with partial.open("wb") as output:
- for chunk in manifest["chunks"]:
- with part_path(stage, chunk["index"]).open("rb") as source:
- while data := source.read(BLOCK):
- output.write(data)
- whole.update(data)
- output.flush()
- os.fsync(output.fileno())
- if partial.stat().st_size != manifest["size"] or whole.hexdigest() != manifest["sha256"]:
- raise TransferError("assembled file hash mismatch; final file was not replaced")
- partial.replace(destination)
- def clean_stage(stage, manifest):
- # Remove only files owned by this transfer, never recurse over an unknown tree.
- for chunk in manifest["chunks"]:
- path = part_path(stage, chunk["index"])
- path.unlink(missing_ok=True)
- Path(str(path) + ".partial").unlink(missing_ok=True)
- (stage / "MANIFEST.json").unlink(missing_ok=True)
- (stage / "MANIFEST.json.partial").unlink(missing_ok=True)
- try:
- stage.rmdir()
- except OSError:
- pass # Preserve unexpected files.
- def remote_path(value):
- path = Path(value)
- if not path.is_absolute():
- raise ValueError("remote paths must be absolute")
- path = path.resolve()
- if path == REMOTE_ROOT or REMOTE_ROOT not in path.parents:
- raise ValueError("remote artifact paths must remain under /data/prod2u")
- return path
- def serve(request, input_stream=None, output_stream=None):
- operation = request["operation"]
- if operation == "describe":
- return describe(remote_path(request["source"]), request["chunk_bytes"])
- if operation == "get":
- source, chunk = remote_path(request["source"]), request["chunk"]
- if not 0 < chunk["size"] <= MAX_CHUNK or chunk["offset"] < 0:
- raise ValueError("invalid requested chunk range")
- sha = hashlib.sha256()
- with source.open("rb") as stream:
- stream.seek(chunk["offset"])
- remaining = chunk["size"]
- while remaining:
- data = stream.read(min(BLOCK, remaining))
- if not data:
- raise TransferError("source truncated during transfer", 3)
- output_stream.write(data)
- sha.update(data)
- remaining -= len(data)
- if sha.hexdigest() != chunk["sha256"]:
- raise TransferError("source chunk changed during transfer", 3)
- return None
- destination = remote_path(request["destination"])
- with destination_lock(destination):
- if operation == "prepare":
- manifest = validate_manifest(request["manifest"])
- if guard_destination(destination, manifest["size"], manifest["sha256"], request.get("replace", False)):
- return {"complete": True, "missing": []}
- stage = prepare_stage(destination, manifest)
- return {"complete": False, "missing": missing_parts(stage, manifest)}
- valid_sha(request["sha256"])
- stage = stage_path(destination, request["sha256"], request["chunk_bytes"])
- if operation == "finalize" and matched(destination, request["size"], request["sha256"]):
- return {"complete": True}
- manifest = validate_manifest(json.loads((stage / "MANIFEST.json").read_text(encoding="utf-8")))
- if manifest["sha256"] != request["sha256"] or manifest["chunk_bytes"] != request["chunk_bytes"]:
- raise TransferError("transfer identity mismatch")
- if operation == "put":
- index = request["index"]
- if not isinstance(index, int) or not 0 <= index < len(manifest["chunks"]):
- raise ValueError("invalid chunk index")
- receive_part(input_stream, stage, manifest["chunks"][index])
- return {"verified": index}
- if operation == "finalize":
- assemble(destination, manifest, stage, request.get("replace", False))
- clean_stage(stage, manifest)
- return {"complete": True}
- raise ValueError("unknown transfer operation")
- class SSH:
- def __init__(self, remote_worker, retries=5):
- self.remote_worker = remote_worker
- self.retries = retries
- self.calls = 0
- def command(self, request):
- encoded = base64.b64encode(json.dumps(request, ensure_ascii=False).encode()).decode()
- null = "NUL" if sys.platform == "win32" else "/dev/null"
- return ["ssh", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=no",
- "-o", "UserKnownHostsFile=" + null, "-o", "GlobalKnownHostsFile=" + null,
- "-o", "UpdateHostKeys=no", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=15",
- "-o", "ServerAliveCountMax=4", "edk2-uefi-lab",
- shlex.join(["python3", self.remote_worker, "--serve", encoded])]
- def request(self, request, source=None, chunk=None, destination=None):
- delays = (2, 5, 10, 20, 30)
- for attempt in range(self.retries + 1):
- self.calls += 1
- output = Path(destination).open("wb") if destination else None
- process = None
- try:
- # Large chunk manifests go over stdin, not the Windows command
- # line (whose length limit is much smaller than large manifests).
- stream_request = source is None
- header = {"operation": "request"} if stream_request else request
- process = subprocess.Popen(self.command(header), stdin=subprocess.PIPE,
- stdout=output or subprocess.PIPE, stderr=subprocess.PIPE)
- if source:
- try:
- with Path(source).open("rb") as stream:
- stream.seek(chunk["offset"])
- remaining = chunk["size"]
- while remaining:
- data = stream.read(min(BLOCK, remaining))
- if not data:
- raise TransferError("local source truncated during upload")
- process.stdin.write(data)
- remaining -= len(data)
- except BrokenPipeError:
- pass
- try:
- process.stdin.close()
- except BrokenPipeError:
- pass
- process.stdin = None
- stdout, stderr = process.communicate(input=json.dumps(request, ensure_ascii=False).encode() if stream_request else None)
- finally:
- if process and process.poll() is None:
- process.kill()
- process.wait()
- if output:
- output.close()
- if process.returncode == 0:
- return json.loads(stdout.decode("utf-8")) if stdout else None
- transport_failure = process.returncode == 255 or not 0 <= process.returncode <= 255
- if not transport_failure or attempt == self.retries:
- code = 255 if transport_failure else process.returncode
- raise TransferError(stderr.decode("utf-8", errors="replace").strip() or "SSH transfer failed", code)
- print(json.dumps({"retry": attempt + 1, "delay_seconds": delays[attempt], "reason": "SSH transport interrupted"}),
- file=sys.stderr, flush=True)
- time.sleep(delays[attempt])
- def progress(index, action):
- print(json.dumps({"chunk": index, "action": action}), file=sys.stderr, flush=True)
- def upload(remote, source, destination, chunk_bytes=DEFAULT_CHUNK, replace=False):
- manifest = describe(source, chunk_bytes)
- prepared = remote.request({"operation": "prepare", "destination": destination, "manifest": manifest, "replace": replace})
- transferred, reused = [], []
- if not prepared["complete"]:
- missing = set(prepared["missing"])
- for chunk in manifest["chunks"]:
- index = chunk["index"]
- if index in missing:
- remote.request({"operation": "put", "destination": destination, "sha256": manifest["sha256"],
- "chunk_bytes": chunk_bytes, "index": index}, source=source, chunk=chunk)
- transferred.append(index)
- progress(index, "transferred")
- else:
- reused.append(index)
- progress(index, "reused")
- remote.request({"operation": "finalize", "destination": destination, "sha256": manifest["sha256"],
- "chunk_bytes": chunk_bytes, "size": manifest["size"], "replace": replace})
- else:
- reused = [chunk["index"] for chunk in manifest["chunks"]]
- return receipt("upload", source, destination, manifest, transferred, reused)
- def download(remote, source, destination, expected_sha256, chunk_bytes=DEFAULT_CHUNK, replace=False):
- valid_sha(expected_sha256)
- manifest = validate_manifest(remote.request({"operation": "describe", "source": source, "chunk_bytes": chunk_bytes}))
- if manifest["sha256"] != expected_sha256:
- raise TransferError("SOURCE_HASH_MISMATCH: source does not match requested artifact")
- destination = Path(destination).resolve()
- transferred, reused = [], []
- with destination_lock(destination):
- if guard_destination(destination, manifest["size"], manifest["sha256"], replace):
- reused = [chunk["index"] for chunk in manifest["chunks"]]
- else:
- stage = prepare_stage(destination, manifest)
- for chunk in manifest["chunks"]:
- index = chunk["index"]
- final = part_path(stage, index)
- if matched(final, chunk["size"], chunk["sha256"]):
- reused.append(index)
- progress(index, "reused")
- continue
- partial = Path(str(final) + ".partial")
- remote.request({"operation": "get", "source": source, "chunk": chunk}, destination=partial)
- if not matched(partial, chunk["size"], chunk["sha256"]):
- raise TransferError("downloaded chunk hash mismatch; earlier verified chunks are retained", 3)
- partial.replace(final)
- transferred.append(index)
- progress(index, "transferred")
- assemble(destination, manifest, stage, replace)
- clean_stage(stage, manifest)
- return receipt("download", source, destination, manifest, transferred, reused)
- def receipt(direction, source, destination, manifest, transferred, reused):
- return {"schema": "prod2u-transfer-receipt-v1", "status": "PASS", "scope": "file byte integrity",
- "direction": direction, "source": str(source), "destination": str(destination),
- "size": manifest["size"], "sha256": manifest["sha256"], "chunk_bytes": manifest["chunk_bytes"],
- "transferred_chunks": transferred, "reused_chunks": reused,
- "verified_bytes_transferred": sum(manifest["chunks"][i]["size"] for i in transferred)}
- def main(argv=None):
- for stream in (sys.stdout, sys.stderr):
- if hasattr(stream, "reconfigure"):
- stream.reconfigure(encoding="utf-8")
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--serve", help=argparse.SUPPRESS)
- parser.add_argument("--remote-worker", help="exact remote tools/remote_transfer.py path")
- parser.add_argument("--chunk-bytes", type=int, default=DEFAULT_CHUNK)
- parser.add_argument("--retries", type=int, choices=range(6), default=5, help="SSH retries with 2/5/10/20/30s backoff")
- parser.add_argument("--replace", action="store_true", help="explicitly replace a different existing destination")
- sub = parser.add_subparsers(dest="action")
- up = sub.add_parser("upload")
- up.add_argument("source", type=Path)
- up.add_argument("destination")
- down = sub.add_parser("download")
- down.add_argument("source")
- down.add_argument("destination", type=Path)
- down.add_argument("--expected-sha256", required=True)
- args = parser.parse_args(argv)
- try:
- if args.serve:
- if sys.platform != "linux":
- raise ValueError("remote transfer worker runs on the Linux host")
- request = json.loads(base64.b64decode(args.serve))
- if request["operation"] == "request":
- request = json.load(sys.stdin.buffer)
- result = serve(request, sys.stdin.buffer, sys.stdout.buffer)
- else:
- if not args.remote_worker or not args.action:
- parser.error("upload/download and --remote-worker are required")
- remote = SSH(args.remote_worker, args.retries)
- if args.action == "upload":
- result = upload(remote, args.source.resolve(), args.destination, args.chunk_bytes, args.replace)
- else:
- result = download(remote, args.source, args.destination, args.expected_sha256.lower(), args.chunk_bytes, args.replace)
- if result is not None:
- print(json.dumps(result, indent=2, ensure_ascii=False))
- return 0
- except (ValueError, OSError, KeyError, TransferError) as error:
- print(str(error), file=sys.stderr)
- return error.code if isinstance(error, TransferError) else 2
- if __name__ == "__main__":
- raise SystemExit(main())
|