remote_transfer.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. #!/usr/bin/env python3
  2. """Resumable, hash-verified artifact upload/download over the existing LAN SSH.
  3. Both Windows transfer adapters forward here. Source synchronization remains Git.
  4. Only verified chunks are reused; final files appear after whole-file verification.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import base64
  9. from contextlib import contextmanager
  10. import hashlib
  11. import json
  12. import os
  13. from pathlib import Path
  14. import re
  15. import shlex
  16. import subprocess
  17. import sys
  18. import time
  19. REMOTE_ROOT = Path("/data/prod2u")
  20. MIN_CHUNK = 65536
  21. MAX_CHUNK = 256 * 1024 * 1024
  22. DEFAULT_CHUNK = 4 * 1024 * 1024
  23. BLOCK = 1024 * 1024
  24. class TransferError(RuntimeError):
  25. def __init__(self, message, code=2):
  26. super().__init__(message)
  27. self.code = code
  28. def file_sha(path):
  29. with Path(path).open("rb") as stream:
  30. return hashlib.file_digest(stream, "sha256").hexdigest()
  31. def valid_sha(value):
  32. if not isinstance(value, str) or not re.fullmatch("[0-9a-f]{64}", value):
  33. raise ValueError("expected a lowercase SHA256 digest")
  34. def validate_manifest(manifest):
  35. valid_sha(manifest["sha256"])
  36. size, chunk_bytes = manifest["size"], manifest["chunk_bytes"]
  37. if not isinstance(size, int) or size < 0 or not MIN_CHUNK <= chunk_bytes <= MAX_CHUNK:
  38. raise ValueError("invalid file size or chunk size (64 KiB..256 MiB)")
  39. offset = 0
  40. for index, chunk in enumerate(manifest["chunks"]):
  41. valid_sha(chunk["sha256"])
  42. if (chunk["index"] != index or chunk["offset"] != offset
  43. or chunk["size"] != min(chunk_bytes, size - offset) or chunk["size"] <= 0):
  44. raise ValueError("invalid chunk index, size or offset")
  45. offset += chunk["size"]
  46. if offset != size:
  47. raise ValueError("chunk manifest does not cover the file")
  48. return manifest
  49. def describe(source, chunk_bytes=DEFAULT_CHUNK):
  50. if not MIN_CHUNK <= chunk_bytes <= MAX_CHUNK:
  51. raise ValueError("chunk size must be 64 KiB..256 MiB")
  52. source = Path(source)
  53. before = source.stat()
  54. whole = hashlib.sha256()
  55. chunks = []
  56. offset = 0
  57. with source.open("rb") as stream:
  58. while offset < before.st_size:
  59. length = min(chunk_bytes, before.st_size - offset)
  60. sha = hashlib.sha256()
  61. remaining = length
  62. while remaining:
  63. data = stream.read(min(BLOCK, remaining))
  64. if not data:
  65. raise TransferError("source changed while computing manifest")
  66. sha.update(data)
  67. whole.update(data)
  68. remaining -= len(data)
  69. chunks.append({"index": len(chunks), "offset": offset, "size": length, "sha256": sha.hexdigest()})
  70. offset += length
  71. if stream.read(1):
  72. raise TransferError("source grew while computing manifest")
  73. after = source.stat()
  74. if (before.st_size, before.st_mtime_ns, before.st_ino) != (after.st_size, after.st_mtime_ns, after.st_ino):
  75. raise TransferError("source changed while computing manifest")
  76. return validate_manifest({"schema": "prod2u-transfer-v1", "size": offset,
  77. "sha256": whole.hexdigest(), "chunk_bytes": chunk_bytes, "chunks": chunks})
  78. def matched(path, size, sha):
  79. path = Path(path)
  80. return path.is_file() and path.stat().st_size == size and file_sha(path) == sha
  81. def stage_path(destination, sha, chunk_bytes):
  82. identity = json.dumps([str(Path(destination).resolve()), sha, chunk_bytes], ensure_ascii=False).encode()
  83. return Path(destination).parent / ("transfer-parts-" + hashlib.sha256(identity).hexdigest()[:24])
  84. def part_path(stage, index):
  85. return stage / ("part-" + str(index).zfill(6))
  86. @contextmanager
  87. def destination_lock(destination):
  88. path = Path(str(destination) + ".transfer.lock")
  89. path.parent.mkdir(parents=True, exist_ok=True)
  90. with path.open("a+b") as stream:
  91. if sys.platform == "win32":
  92. import msvcrt
  93. stream.seek(0)
  94. if not stream.read(1):
  95. stream.write(b"0")
  96. stream.flush()
  97. stream.seek(0)
  98. msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1)
  99. try:
  100. yield
  101. finally:
  102. stream.seek(0)
  103. msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
  104. else:
  105. import fcntl
  106. fcntl.flock(stream, fcntl.LOCK_EX)
  107. yield
  108. def prepare_stage(destination, manifest):
  109. validate_manifest(manifest)
  110. stage = stage_path(destination, manifest["sha256"], manifest["chunk_bytes"])
  111. stage.mkdir(parents=True, exist_ok=True)
  112. path = stage / "MANIFEST.json"
  113. if path.exists():
  114. if json.loads(path.read_text(encoding="utf-8")) != manifest:
  115. raise TransferError("transfer staging manifest conflict")
  116. else:
  117. temporary = stage / "MANIFEST.json.partial"
  118. temporary.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
  119. temporary.replace(path)
  120. return stage
  121. def missing_parts(stage, manifest):
  122. return [chunk["index"] for chunk in manifest["chunks"]
  123. if not matched(part_path(stage, chunk["index"]), chunk["size"], chunk["sha256"])]
  124. def guard_destination(destination, size, sha, replace):
  125. if destination.exists():
  126. if matched(destination, size, sha):
  127. return True
  128. if not replace:
  129. raise TransferError("DESTINATION_CONFLICT: existing file differs; choose a new path or explicit --replace")
  130. return False
  131. def receive_part(stream, stage, chunk):
  132. final = part_path(stage, chunk["index"])
  133. partial = Path(str(final) + ".partial")
  134. sha = hashlib.sha256()
  135. remaining = chunk["size"]
  136. with partial.open("wb") as output:
  137. while remaining:
  138. data = stream.read(min(BLOCK, remaining))
  139. if not data:
  140. raise TransferError("INCOMPLETE_CHUNK: verified earlier chunks remain available", 3)
  141. output.write(data)
  142. sha.update(data)
  143. remaining -= len(data)
  144. if stream.read(1):
  145. raise TransferError("chunk contains extra bytes", 3)
  146. output.flush()
  147. os.fsync(output.fileno())
  148. if sha.hexdigest() != chunk["sha256"]:
  149. raise TransferError("CHUNK_HASH_MISMATCH: chunk was not committed", 3)
  150. partial.replace(final)
  151. def assemble(destination, manifest, stage, replace=False):
  152. if guard_destination(destination, manifest["size"], manifest["sha256"], replace):
  153. return
  154. missing = missing_parts(stage, manifest)
  155. if missing:
  156. raise TransferError("missing or corrupt chunks: " + ",".join(map(str, missing)))
  157. partial = Path(str(destination) + ".partial")
  158. whole = hashlib.sha256()
  159. with partial.open("wb") as output:
  160. for chunk in manifest["chunks"]:
  161. with part_path(stage, chunk["index"]).open("rb") as source:
  162. while data := source.read(BLOCK):
  163. output.write(data)
  164. whole.update(data)
  165. output.flush()
  166. os.fsync(output.fileno())
  167. if partial.stat().st_size != manifest["size"] or whole.hexdigest() != manifest["sha256"]:
  168. raise TransferError("assembled file hash mismatch; final file was not replaced")
  169. partial.replace(destination)
  170. def clean_stage(stage, manifest):
  171. # Remove only files owned by this transfer, never recurse over an unknown tree.
  172. for chunk in manifest["chunks"]:
  173. path = part_path(stage, chunk["index"])
  174. path.unlink(missing_ok=True)
  175. Path(str(path) + ".partial").unlink(missing_ok=True)
  176. (stage / "MANIFEST.json").unlink(missing_ok=True)
  177. (stage / "MANIFEST.json.partial").unlink(missing_ok=True)
  178. try:
  179. stage.rmdir()
  180. except OSError:
  181. pass # Preserve unexpected files.
  182. def remote_path(value):
  183. path = Path(value)
  184. if not path.is_absolute():
  185. raise ValueError("remote paths must be absolute")
  186. path = path.resolve()
  187. if path == REMOTE_ROOT or REMOTE_ROOT not in path.parents:
  188. raise ValueError("remote artifact paths must remain under /data/prod2u")
  189. return path
  190. def serve(request, input_stream=None, output_stream=None):
  191. operation = request["operation"]
  192. if operation == "describe":
  193. return describe(remote_path(request["source"]), request["chunk_bytes"])
  194. if operation == "get":
  195. source, chunk = remote_path(request["source"]), request["chunk"]
  196. if not 0 < chunk["size"] <= MAX_CHUNK or chunk["offset"] < 0:
  197. raise ValueError("invalid requested chunk range")
  198. sha = hashlib.sha256()
  199. with source.open("rb") as stream:
  200. stream.seek(chunk["offset"])
  201. remaining = chunk["size"]
  202. while remaining:
  203. data = stream.read(min(BLOCK, remaining))
  204. if not data:
  205. raise TransferError("source truncated during transfer", 3)
  206. output_stream.write(data)
  207. sha.update(data)
  208. remaining -= len(data)
  209. if sha.hexdigest() != chunk["sha256"]:
  210. raise TransferError("source chunk changed during transfer", 3)
  211. return None
  212. destination = remote_path(request["destination"])
  213. with destination_lock(destination):
  214. if operation == "prepare":
  215. manifest = validate_manifest(request["manifest"])
  216. if guard_destination(destination, manifest["size"], manifest["sha256"], request.get("replace", False)):
  217. return {"complete": True, "missing": []}
  218. stage = prepare_stage(destination, manifest)
  219. return {"complete": False, "missing": missing_parts(stage, manifest)}
  220. valid_sha(request["sha256"])
  221. stage = stage_path(destination, request["sha256"], request["chunk_bytes"])
  222. if operation == "finalize" and matched(destination, request["size"], request["sha256"]):
  223. return {"complete": True}
  224. manifest = validate_manifest(json.loads((stage / "MANIFEST.json").read_text(encoding="utf-8")))
  225. if manifest["sha256"] != request["sha256"] or manifest["chunk_bytes"] != request["chunk_bytes"]:
  226. raise TransferError("transfer identity mismatch")
  227. if operation == "put":
  228. index = request["index"]
  229. if not isinstance(index, int) or not 0 <= index < len(manifest["chunks"]):
  230. raise ValueError("invalid chunk index")
  231. receive_part(input_stream, stage, manifest["chunks"][index])
  232. return {"verified": index}
  233. if operation == "finalize":
  234. assemble(destination, manifest, stage, request.get("replace", False))
  235. clean_stage(stage, manifest)
  236. return {"complete": True}
  237. raise ValueError("unknown transfer operation")
  238. class SSH:
  239. def __init__(self, remote_worker, retries=5):
  240. self.remote_worker = remote_worker
  241. self.retries = retries
  242. self.calls = 0
  243. def command(self, request):
  244. encoded = base64.b64encode(json.dumps(request, ensure_ascii=False).encode()).decode()
  245. null = "NUL" if sys.platform == "win32" else "/dev/null"
  246. return ["ssh", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=no",
  247. "-o", "UserKnownHostsFile=" + null, "-o", "GlobalKnownHostsFile=" + null,
  248. "-o", "UpdateHostKeys=no", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=15",
  249. "-o", "ServerAliveCountMax=4", "edk2-uefi-lab",
  250. shlex.join(["python3", self.remote_worker, "--serve", encoded])]
  251. def request(self, request, source=None, chunk=None, destination=None):
  252. delays = (2, 5, 10, 20, 30)
  253. for attempt in range(self.retries + 1):
  254. self.calls += 1
  255. output = Path(destination).open("wb") if destination else None
  256. process = None
  257. try:
  258. # Large chunk manifests go over stdin, not the Windows command
  259. # line (whose length limit is much smaller than large manifests).
  260. stream_request = source is None
  261. header = {"operation": "request"} if stream_request else request
  262. process = subprocess.Popen(self.command(header), stdin=subprocess.PIPE,
  263. stdout=output or subprocess.PIPE, stderr=subprocess.PIPE)
  264. if source:
  265. try:
  266. with Path(source).open("rb") as stream:
  267. stream.seek(chunk["offset"])
  268. remaining = chunk["size"]
  269. while remaining:
  270. data = stream.read(min(BLOCK, remaining))
  271. if not data:
  272. raise TransferError("local source truncated during upload")
  273. process.stdin.write(data)
  274. remaining -= len(data)
  275. except BrokenPipeError:
  276. pass
  277. try:
  278. process.stdin.close()
  279. except BrokenPipeError:
  280. pass
  281. process.stdin = None
  282. stdout, stderr = process.communicate(input=json.dumps(request, ensure_ascii=False).encode() if stream_request else None)
  283. finally:
  284. if process and process.poll() is None:
  285. process.kill()
  286. process.wait()
  287. if output:
  288. output.close()
  289. if process.returncode == 0:
  290. return json.loads(stdout.decode("utf-8")) if stdout else None
  291. transport_failure = process.returncode == 255 or not 0 <= process.returncode <= 255
  292. if not transport_failure or attempt == self.retries:
  293. code = 255 if transport_failure else process.returncode
  294. raise TransferError(stderr.decode("utf-8", errors="replace").strip() or "SSH transfer failed", code)
  295. print(json.dumps({"retry": attempt + 1, "delay_seconds": delays[attempt], "reason": "SSH transport interrupted"}),
  296. file=sys.stderr, flush=True)
  297. time.sleep(delays[attempt])
  298. def progress(index, action):
  299. print(json.dumps({"chunk": index, "action": action}), file=sys.stderr, flush=True)
  300. def upload(remote, source, destination, chunk_bytes=DEFAULT_CHUNK, replace=False):
  301. manifest = describe(source, chunk_bytes)
  302. prepared = remote.request({"operation": "prepare", "destination": destination, "manifest": manifest, "replace": replace})
  303. transferred, reused = [], []
  304. if not prepared["complete"]:
  305. missing = set(prepared["missing"])
  306. for chunk in manifest["chunks"]:
  307. index = chunk["index"]
  308. if index in missing:
  309. remote.request({"operation": "put", "destination": destination, "sha256": manifest["sha256"],
  310. "chunk_bytes": chunk_bytes, "index": index}, source=source, chunk=chunk)
  311. transferred.append(index)
  312. progress(index, "transferred")
  313. else:
  314. reused.append(index)
  315. progress(index, "reused")
  316. remote.request({"operation": "finalize", "destination": destination, "sha256": manifest["sha256"],
  317. "chunk_bytes": chunk_bytes, "size": manifest["size"], "replace": replace})
  318. else:
  319. reused = [chunk["index"] for chunk in manifest["chunks"]]
  320. return receipt("upload", source, destination, manifest, transferred, reused)
  321. def download(remote, source, destination, expected_sha256, chunk_bytes=DEFAULT_CHUNK, replace=False):
  322. valid_sha(expected_sha256)
  323. manifest = validate_manifest(remote.request({"operation": "describe", "source": source, "chunk_bytes": chunk_bytes}))
  324. if manifest["sha256"] != expected_sha256:
  325. raise TransferError("SOURCE_HASH_MISMATCH: source does not match requested artifact")
  326. destination = Path(destination).resolve()
  327. transferred, reused = [], []
  328. with destination_lock(destination):
  329. if guard_destination(destination, manifest["size"], manifest["sha256"], replace):
  330. reused = [chunk["index"] for chunk in manifest["chunks"]]
  331. else:
  332. stage = prepare_stage(destination, manifest)
  333. for chunk in manifest["chunks"]:
  334. index = chunk["index"]
  335. final = part_path(stage, index)
  336. if matched(final, chunk["size"], chunk["sha256"]):
  337. reused.append(index)
  338. progress(index, "reused")
  339. continue
  340. partial = Path(str(final) + ".partial")
  341. remote.request({"operation": "get", "source": source, "chunk": chunk}, destination=partial)
  342. if not matched(partial, chunk["size"], chunk["sha256"]):
  343. raise TransferError("downloaded chunk hash mismatch; earlier verified chunks are retained", 3)
  344. partial.replace(final)
  345. transferred.append(index)
  346. progress(index, "transferred")
  347. assemble(destination, manifest, stage, replace)
  348. clean_stage(stage, manifest)
  349. return receipt("download", source, destination, manifest, transferred, reused)
  350. def receipt(direction, source, destination, manifest, transferred, reused):
  351. return {"schema": "prod2u-transfer-receipt-v1", "status": "PASS", "scope": "file byte integrity",
  352. "direction": direction, "source": str(source), "destination": str(destination),
  353. "size": manifest["size"], "sha256": manifest["sha256"], "chunk_bytes": manifest["chunk_bytes"],
  354. "transferred_chunks": transferred, "reused_chunks": reused,
  355. "verified_bytes_transferred": sum(manifest["chunks"][i]["size"] for i in transferred)}
  356. def main(argv=None):
  357. for stream in (sys.stdout, sys.stderr):
  358. if hasattr(stream, "reconfigure"):
  359. stream.reconfigure(encoding="utf-8")
  360. parser = argparse.ArgumentParser(description=__doc__)
  361. parser.add_argument("--serve", help=argparse.SUPPRESS)
  362. parser.add_argument("--remote-worker", help="exact remote tools/remote_transfer.py path")
  363. parser.add_argument("--chunk-bytes", type=int, default=DEFAULT_CHUNK)
  364. parser.add_argument("--retries", type=int, choices=range(6), default=5, help="SSH retries with 2/5/10/20/30s backoff")
  365. parser.add_argument("--replace", action="store_true", help="explicitly replace a different existing destination")
  366. sub = parser.add_subparsers(dest="action")
  367. up = sub.add_parser("upload")
  368. up.add_argument("source", type=Path)
  369. up.add_argument("destination")
  370. down = sub.add_parser("download")
  371. down.add_argument("source")
  372. down.add_argument("destination", type=Path)
  373. down.add_argument("--expected-sha256", required=True)
  374. args = parser.parse_args(argv)
  375. try:
  376. if args.serve:
  377. if sys.platform != "linux":
  378. raise ValueError("remote transfer worker runs on the Linux host")
  379. request = json.loads(base64.b64decode(args.serve))
  380. if request["operation"] == "request":
  381. request = json.load(sys.stdin.buffer)
  382. result = serve(request, sys.stdin.buffer, sys.stdout.buffer)
  383. else:
  384. if not args.remote_worker or not args.action:
  385. parser.error("upload/download and --remote-worker are required")
  386. remote = SSH(args.remote_worker, args.retries)
  387. if args.action == "upload":
  388. result = upload(remote, args.source.resolve(), args.destination, args.chunk_bytes, args.replace)
  389. else:
  390. result = download(remote, args.source, args.destination, args.expected_sha256.lower(), args.chunk_bytes, args.replace)
  391. if result is not None:
  392. print(json.dumps(result, indent=2, ensure_ascii=False))
  393. return 0
  394. except (ValueError, OSError, KeyError, TransferError) as error:
  395. print(str(error), file=sys.stderr)
  396. return error.code if isinstance(error, TransferError) else 2
  397. if __name__ == "__main__":
  398. raise SystemExit(main())