"""04 SNAPSHOT + RESTORE. Snapshot a clean container, let an agent trash it, restore from the snapshot. This is the "snapshot it, nuke it" slide, live: you always have a clean state one command away, no matter what the agent did to the box. Run: python 04_snapshot_restore.py Needs: Docker installed and running. If Docker is missing, this prints the command sequence it WOULD run and exits 0. It never fakes output. """ import shutil import subprocess import sys IMAGE = "python:3.11-slim" CONTAINER = "vcn42-snapshot-demo" SNAPSHOT_TAG = "vcn42-clean-snapshot" def have_docker() -> bool: return shutil.which("docker") is not None def run(cmd: list[str]) -> str: r = subprocess.run(cmd, capture_output=True, text=True, timeout=60) return (r.stdout or r.stderr).strip() def main(): if not have_docker(): print("Docker not found on this machine.") print("What this script WOULD do, in order:") print(f" 1. docker run -d --name {CONTAINER} {IMAGE} sleep 300 # start a clean box") print(f" 2. docker commit {CONTAINER} {SNAPSHOT_TAG} # snapshot it BEFORE any junk") print(f" 3. docker exec {CONTAINER} touch /tmp/junk_file.txt # let the agent make a mess") print(f" 4. docker rm -f {CONTAINER} # trash the whole box") print(f" 5. docker run --rm {SNAPSHOT_TAG} ls /tmp # restore: no junk_file.txt") print("Install Docker Desktop (or the docker CLI) and re-run to see it live.") sys.exit(0) print("== 1. start a clean box ==") run(["docker", "rm", "-f", CONTAINER]) # clear any leftover from a prior run print(run(["docker", "run", "-d", "--name", CONTAINER, IMAGE, "sleep", "300"])) print("\n== 2. snapshot it clean, before any junk ==") print(run(["docker", "commit", CONTAINER, SNAPSHOT_TAG])) print("\n== 3. an agent messes up the box ==") print(run(["docker", "exec", CONTAINER, "touch", "/tmp/junk_file.txt"])) dirty = run(["docker", "exec", CONTAINER, "ls", "/tmp"]) print(f"Files in /tmp now: {dirty}") print("\n== 4. trash the messy box entirely ==") print(run(["docker", "rm", "-f", CONTAINER])) print("\n== 5. restore from the clean snapshot ==") clean = run(["docker", "run", "--rm", SNAPSHOT_TAG, "ls", "/tmp"]) print(f"Files in /tmp from the snapshot: '{clean}' (empty, the junk never happened)") run(["docker", "rmi", SNAPSHOT_TAG]) # tidy up the demo image print("\nSnapshot restored, box gone. That's the pattern: snapshot clean, trash freely, restore always.") if __name__ == "__main__": main()