Files
kiri/tests/disk-grow.py
T
Precious Okwu 3db7378e5b CI & release: enforce executable regression checks, PR gates, Windows unit tests, and Mac release gate (#1128)
* CI & release: enforce executable regression checks, PR gates, Windows unit tests, and Mac release gate

* Compose: keep empty environment variables distinct instead of gluing onto preceding entry
2026-12-02 02:41:04 +01:00

226 lines
9.6 KiB
Python

#!/usr/bin/env python3
"""VM disk growth, dirty ext4 repair, and rapid restart checks on macOS (#384, #1118).
cargo xtask host && cargo xtask guest
python3 tests/disk-grow.py [target/release/kiri] [--guest-dir guest/out]
"""
import argparse
import os
from pathlib import Path
import platform
import plistlib
import secrets
import shutil
import struct
import subprocess
import tempfile
import time
EXT4_SUPER_OFFSET = 1024
EXT4_SUPER_LEN = 1024
EXT4_SUPER_MAGIC = 0xEF53
EXT4_VALID_FS = 0x0001
EXT4_ERROR_FS = 0x0002
EXT4_RO_COMPAT_METADATA_CSUM = 0x0400
def ext4_superblock_csum(sb: bytes) -> int:
"""Raw Castagnoli CRC32C over sb[:0x3fc] seeded with 0xffffffff (no final XOR)."""
crc = 0xFFFFFFFF
for byte in sb[:0x3FC]:
crc ^= byte
for _ in range(8):
mask = -(crc & 1) & 0xFFFFFFFF
crc = (crc >> 1) ^ (0x82F63B78 & mask)
return crc
def read_superblock_state(image: Path) -> int:
with image.open("rb") as fh:
fh.seek(EXT4_SUPER_OFFSET)
sb = fh.read(EXT4_SUPER_LEN)
magic, state = struct.unpack_from("<HH", sb, 0x38)
assert magic == EXT4_SUPER_MAGIC, f"unexpected ext4 magic 0x{magic:04x}"
return state
def stamp_ext4_error_fs(image: Path) -> None:
with image.open("r+b") as fh:
fh.seek(EXT4_SUPER_OFFSET)
sb = bytearray(fh.read(EXT4_SUPER_LEN))
magic, state = struct.unpack_from("<HH", sb, 0x38)
assert magic == EXT4_SUPER_MAGIC, f"unexpected ext4 magic 0x{magic:04x}"
ro_compat = struct.unpack_from("<I", sb, 0x64)[0]
if ro_compat & EXT4_RO_COMPAT_METADATA_CSUM:
stored = struct.unpack_from("<I", sb, 0x3FC)[0]
assert stored == ext4_superblock_csum(sb), "superblock CRC32C mismatch before stamping"
struct.pack_into("<H", sb, 0x3A, state | EXT4_ERROR_FS)
if ro_compat & EXT4_RO_COMPAT_METADATA_CSUM:
struct.pack_into("<I", sb, 0x3FC, ext4_superblock_csum(sb))
fh.seek(EXT4_SUPER_OFFSET)
fh.write(sb)
fh.flush()
os.fsync(fh.fileno())
def main():
if platform.system() != "Darwin":
print("SKIP VM disk growth: macOS only")
return
repo = Path(__file__).resolve().parent.parent
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("binary", nargs="?", default=repo / "target/release/kiri", type=Path)
parser.add_argument("--guest-dir", default=repo / "guest/out", type=Path)
args = parser.parse_args()
feature = "disk" + secrets.token_hex(4)
state = Path.home() / (".kiri-" + feature)
assert not state.exists()
env = os.environ.copy()
for key in ["DOCKER_CONTEXT", "DOCKER_HOST", "KIRI_DISK_GB"]:
env.pop(key, None)
with tempfile.TemporaryDirectory(prefix="kiri-disk-", dir="/tmp") as directory:
work = Path(directory).resolve()
contents = work / "Kiri Disk.app/Contents"
(contents / "MacOS").mkdir(parents=True)
binary = contents / "MacOS/kiri"
shutil.copy2(args.binary.resolve(), binary)
(contents / "Info.plist").write_bytes(plistlib.dumps({
"CFBundleIdentifier": "dev.kiri.app." + feature,
"CFBundleExecutable": "kiri",
}))
subprocess.run(
["codesign", "--force", "--sign", "-", "--entitlements",
str(repo / "crates/kiri/kiri.entitlements"), str(contents.parent)],
check=True, capture_output=True, text=True,
)
socket = work / "docker.sock"
env.update(KIRI_SOCKET=str(socket), KIRI_DATA_DIR=str(work / "data"),
KIRI_GUEST_DIR=str(args.guest_dir.resolve()), KIRI_NO_FINDER="1",
KIRI_IDLE_SECS="0", KIRI_MEMORY_MIB="1024")
proc = None
log = (work / "daemon.log").open("w+")
def docker(*command):
return subprocess.run(["docker", "--host", "unix://" + str(socket), *command],
env=env, capture_output=True, text=True, check=True,
timeout=90).stdout.strip()
def kiri(*command):
return subprocess.run([str(binary), *command],
env=env, capture_output=True, text=True, check=True,
timeout=90).stdout.strip()
def stop():
nonlocal proc
if proc is not None:
proc.terminate()
try:
proc.wait(timeout=20)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
raise AssertionError("daemon did not stop cleanly")
proc = None
def start(size):
nonlocal proc
settings = dict(env)
if size is not None:
settings["KIRI_DISK_GB"] = str(size)
proc = subprocess.Popen([str(binary), "daemon"], env=settings, stdout=log, stderr=log)
for _ in range(150):
assert proc.poll() is None, "daemon exited before becoming ready"
if socket.exists():
try:
docker("info")
return
except subprocess.CalledProcessError:
pass
time.sleep(0.1)
raise AssertionError("daemon did not become ready")
def volume(command):
return docker("run", "--rm", "-v", "disk-grow:/data", "alpine", "sh", "-c", command)
def check_capacity(size, checksum):
assert volume("sha256sum /data/keep").split()[0] == checksum, "volume data changed"
blocks, block_size = map(int, volume("stat -f -c '%b %S' /data").split())
actual = blocks * block_size
assert size * 0.9 * (1 << 30) < actual <= size * (1 << 30), actual
image = Path(env["KIRI_DATA_DIR"]) / "vm/data.img"
info = image.stat()
assert info.st_size == size * (1 << 30), info.st_size
assert info.st_blocks * 512 < info.st_size // 8, "image is no longer sparse"
print(f"PASS {size} GiB image and filesystem ({actual / (1 << 30):.1f} GiB); volume data preserved", flush=True)
try:
start(None)
# Boot filesystem tools must be unlinked from guest tmpfs once /var/lib/kiri is mounted.
docker("run", "--rm", "--privileged", "--pid=host", "alpine",
"sh", "-c",
"test ! -e /proc/1/root/sbin/e2fsck && test ! -e /proc/1/root/sbin/resize2fs && test -d /proc/1/root/lib/modules")
print("PASS boot ext4 tools unlinked from guest tmpfs after mount", flush=True)
checksum = volume("dd if=/dev/urandom of=/data/keep bs=1048576 count=1 2>/dev/null; sha256sum /data/keep").split()[0]
check_capacity(64, checksum)
stop()
clean_state = read_superblock_state(work / "data/vm/data.img")
assert (clean_state & EXT4_ERROR_FS) == 0, f"unexpected EXT4_ERROR_FS: 0x{clean_state:04x}"
assert (clean_state & EXT4_VALID_FS) != 0, f"expected EXT4_VALID_FS after clean VM shutdown: 0x{clean_state:04x}"
print("PASS clean VM shutdown unmounts /var/lib/kiri with EXT4_VALID_FS", flush=True)
for setting in [128, 96, None]:
start(setting)
check_capacity(128, checksum)
stop()
print("PASS growth, smaller setting, and removed setting across VM restarts", flush=True)
# A fresh install must grow its copy of the template as well.
env["KIRI_DATA_DIR"] = str(work / "fresh")
start(128)
volume("echo fresh > /data/keep")
fresh = (work / "fresh/vm/data.img").stat()
blocks, block_size = map(int, volume("stat -f -c '%b %S' /data").split())
assert fresh.st_size == 128 << 30
assert blocks * block_size > 115 << 30
stop()
print("PASS new disk starts at configured capacity", flush=True)
# Issue #1118: a 64 GiB data.img carrying EXT4_ERROR_FS must be repaired
# by e2fsck and resized offline to 128 GiB, then survive 5 back-to-back
# `kiri engine restart` cycles under active disk writes without O_EXLOCK races.
env["KIRI_DATA_DIR"] = str(work / "dirty")
start(None)
dirty_sum = volume("dd if=/dev/urandom of=/data/keep bs=1048576 count=2 2>/dev/null; sha256sum /data/keep").split()[0]
check_capacity(64, dirty_sum)
stop()
dirty_img = work / "dirty/vm/data.img"
stamp_ext4_error_fs(dirty_img)
assert (read_superblock_state(dirty_img) & EXT4_ERROR_FS) != 0
start(128)
check_capacity(128, dirty_sum)
for cycle in range(1, 6):
volume(f"dd if=/dev/urandom of=/data/churn-{cycle} bs=1048576 count=16 2>/dev/null && sync")
kiri("engine", "restart")
check_capacity(128, dirty_sum)
stop()
repaired_state = read_superblock_state(dirty_img)
assert (repaired_state & EXT4_ERROR_FS) == 0, f"EXT4_ERROR_FS remained set: 0x{repaired_state:04x}"
assert (repaired_state & EXT4_VALID_FS) != 0, f"EXT4_VALID_FS missing after stop: 0x{repaired_state:04x}"
print("PASS dirty EXT4_ERROR_FS repaired, grown to 128 GiB, and survived 5x kiri engine restart", flush=True)
except Exception:
log.flush()
print((work / "daemon.log").read_text())
raise
finally:
stop()
log.close()
if state.exists():
shutil.rmtree(state)
if __name__ == "__main__":
main()