deploy_to_delivery_pc.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python3
  2. """Copy an explicit release directory to Windows and compare every delivered SHA256."""
  3. from __future__ import annotations
  4. import argparse
  5. import base64
  6. import json
  7. from pathlib import Path
  8. import subprocess
  9. def ps(text: str) -> str:
  10. return "powershell -NoProfile -NonInteractive -EncodedCommand " + base64.b64encode(text.encode("utf-16le")).decode()
  11. def quote(text: str) -> str:
  12. return "'" + text.replace("'", "''") + "'"
  13. def main(argv=None) -> int:
  14. parser = argparse.ArgumentParser(description=__doc__)
  15. parser.add_argument("--source-dir", type=Path, required=True)
  16. parser.add_argument("--destination", required=True, help="new absolute Windows directory")
  17. parser.add_argument("--host", default="administrator@192.168.2.24")
  18. args = parser.parse_args(argv)
  19. source = args.source_dir.resolve()
  20. manifest = source / "DELIVERY-SHA256.json"
  21. if not manifest.is_file() or not json.loads(manifest.read_text()):
  22. parser.error("source-dir needs the nonempty packaging checksum manifest")
  23. log = source.parent / (source.name + "-delivery.log")
  24. receipt = source.parent / (source.name + "-delivery-receipt.json")
  25. def run(command):
  26. with log.open("a") as stream:
  27. subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT, check=True)
  28. destination = args.destination.rstrip("/\\")
  29. scp_destination = destination.replace("\\", "/")
  30. run(["ssh", "-o", "ConnectTimeout=10", args.host,
  31. ps("$ErrorActionPreference='Stop'; $p=" + quote(destination)
  32. + "; if (Test-Path $p) {throw 'Use a new release directory'}; New-Item -ItemType Directory -Path $p | Out-Null")])
  33. for child in sorted(source.iterdir()):
  34. run(["scp", "-r", str(child), args.host + ":" + scp_destination + "/"])
  35. verify = r'''
  36. $ErrorActionPreference='Stop'
  37. $ProgressPreference='SilentlyContinue'
  38. $root=ROOT_VALUE
  39. $items=Get-Content -LiteralPath (Join-Path $root 'DELIVERY-SHA256.json') -Raw -Encoding UTF8 | ConvertFrom-Json
  40. $verified=@()
  41. foreach ($item in $items) {
  42. $path=Join-Path $root $item.path
  43. $actual=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
  44. $size=(Get-Item -LiteralPath $path).Length
  45. if ($actual -ne $item.sha256 -or $size -ne $item.size_bytes) {throw ('SHA or size mismatch: '+$item.path)}
  46. $verified+=@{path=$item.path;sha256=$actual;size_bytes=$size}
  47. }
  48. $result=@{status='PASS';scope='file transfer and SHA256 comparison';host=$env:COMPUTERNAME;destination=$root;
  49. verified_files=$verified.Count;files=$verified;hardware_validation='NOT_RUN_BY_DELIVERY';utc=[DateTime]::UtcNow.ToString('o')}
  50. $result | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $root 'DELIVERY-RECEIPT.json') -Encoding UTF8
  51. Write-Output ('DELIVERY_SHA256_PASS '+$verified.Count)
  52. '''.replace("ROOT_VALUE", quote(destination))
  53. run(["ssh", "-o", "ConnectTimeout=10", args.host, ps(verify)])
  54. run(["scp", args.host + ":" + scp_destination + "/DELIVERY-RECEIPT.json", str(receipt)])
  55. result = json.loads(receipt.read_text(encoding="utf-8-sig"))
  56. if result.get("status") != "PASS":
  57. raise ValueError("remote delivery verification failed")
  58. print(json.dumps({key: result[key] for key in ("status", "host", "destination", "verified_files")}, ensure_ascii=False))
  59. print(str(receipt))
  60. return 0
  61. if __name__ == "__main__":
  62. raise SystemExit(main())