Chương 06 — Container Hóa Tầng nhân (Namespaces/cgroups v2/OverlayFS), Kiến trúc Docker vs. Podman, BuildKit + uv, Bảo mật Chuỗi cung ứng, Private Registry & Docker Compose / Testcontainers
Từ 7 Namespaces (pivot_root/subuid) & Firecracker, Bẫy cgroups v2 CFS (p99 10.94x) & Exit 137 vs 143, OverlayFS 2W (920 vs 1,720 MB) đến BuildKit+uv (18.76x), Harbor sha256 (-82.76%), Dockerfile 100/100 HARDENED & Compose internal:true + Testcontainers.
Unit ID:
T2-P1-U06
Track & Part: Track 2 (EDAI) — Part 1: Software, Backend & Container Engineering Foundations (part-01-software-systems-foundations)
Truy xuất Giáo trình Gốc (R28&AIDE 1 R27): Bài 6 Fundamentals of Engineering — Containerization & Orchestration (Introduction to VM and containers,Docker & architecture design,Understand different containerization technologies,Docker commands,Docker volumes and network,Private Artifact Registry,Docker Compose,A comprehensive guideline to build, run, optimize and manage containers,Dockerize API + Compose + Container-based Application Testing) trong 02-track-edai-raw-curriculum.md và đề cương nâng cấp 02-track-2-edai-sota-syllabus.md
Bài thực hành Song hành (Lab 05):labs/lab-05-docker-compose-and-testcontainers/(container_ops_lab)
Tình huống Mở đầu: Năm Thảm họa Container Sản xuất Khi Đóng gói Hệ thống AI#
Cấu hình phát triển FROM python:latest, COPY . ., RUN pip install ... chạy ổn trên máy cá nhân, nhưng sẽ kích hoạt ngay năm sự cố sản xuất kinh điển:
- Điều tiết CFS
cgroups v2Kéop99Tăng10.94xDù CPU Trung bình Thấp: Cấpcpu.max = 100000 100000(1.0 vCPU) trên máy16lõi mà không ghimOMP_NUM_THREADSkhiến16luồng đốt hết ngân sách100 mstrong6.25 ms, rồi bị nhân treo cứng93.75 mscòn lại. Trêncontainer_ops_lab,p99nhảy từ16.1 mslên176.08 ms(10.94x); còn vượtmemory.max(512 MiB) hoặc/dev/shm64 MiBkích hoạtSIGKILL(Exit Code 137). - Phình Dung lượng
2WTrênOverlayFS& Ảo giácRUN rm: Sao chép trọng số800 MBrồi chạy riêngRUN chmod/chownbuộc OverlayFS copy-up toàn tệp từlowerdirsangupperdir, đẩy ảnh từ920 MBlên1,720 MB(2.0x). Chạy thêmRUN rm -fchỉ ghi tệp whiteout/models/.wh.model.safetensorskhiến ảnh tải mạng vẫn giữ nguyên1,720.01 MB. - Lộ Bí mật
ARG/ENVTrong7.86 Giây& Phá Cache CI Chậm18.76x: Nghiên cứu Đại học Stony Brook (ACM CCS,300ảnh) cho thấy bot quétdocker history --no-trunckhai thác khóa AWS rò rỉ chỉ sau7.86 giây. Ngoài ra,COPY .trướcpip installphá vỡ lớp thư viện qua10lần sửasrc/(683.0 sso với36.4 skhi táchuv.lock+BuildKit). - Bẫy
PID 1/bin/shNuốtSIGTERM(Exit 137vs143) & Lỗ hổngdocker.sock: Shell-formCMD uvicorn ...biến/bin/sh -cthànhPID 1không chuyển tiếpSIGTERM, gây timeoutSIGKILL(Exit 137) và lỗi502thay vì tắt êm (Exit 143). Đồng thời gắn/var/run/docker.socktrao thẳng quyềnrootmáy chủ cho container. - Đua Khởi động
Compose, Lộ Mạng DB & Đụng độ Cổng5432: Thiếudepends_on: condition: service_healthylàmapisập trước khi PostgreSQL mở cổng; mở mạng WAN cho DB tăng rủi ro tuồn dữ liệu; và DB CI dùng chung gây xung đột cổng5432— đòi hỏi mạng képinternal: truekết hợpTestcontainerscổng động vàRyuk.
Mục tiêu Học tập (Learning Objectives)#
Sau Chương 06 và container_ops_lab (Lab 05), kỹ sư Dữ liệu & AI nắm vững:
- Ảo hóa Tầng nhân &
7Namespaces: Phân biệt Type-1/2 Hypervisor, Container dùng chung nhân và Firecracker microVM (< 5 MiB,<= 125 ms) cho sandbox AI; làm chủPID,NET(veth),MNT(pivot_rootvschrootescape),UTS,IPC(/dev/shm),USER(subuid/subgid),CGROUP. cgroups v2& Tín hiệuPID 1: Tính toáncpu.max(\(Q_{\text{cpu}}, P_{\text{cfs}}\)), phân biệtmemory.highvớimemory.max(Exit 137), và viết exec-form +tiniđạtExit 143.OverlayFS,BuildKit&uv: Chứng minh2Wcopy-up và.wh.*, dùng--mount=type=cache/bind/secret, táchuv.locktrướcCOPY src/, và tránhmuslAlpine (PEP 656) cho wheelmanylinux(PEP 600) bằngslim-bookworm/Distroless/Chainguard Wolfi (glibc).- Chuẩn OCI v1.1,
Podman, Chuỗi Cung ứng &Registry: Đối chiếu Docker daemon với RootlessPodman(conmon/crun/pasta), épUSER >= 10001,--read-only,--cap-drop=ALL, tạo SBOM (SPDX 3.0/CycloneDX 1.6), quétTrivy/Grype, kýCosign v3.0, và khử trùng lặpsha256+@sha256:trênHarbor/GAR. Docker Compose&Testcontainers: Thiết kế DAGservice_healthy, cô lập dữ liệu quainternal: true, kiểm toánDockerfilevsDockerfile.naivequaPyYAML/AST và đạt16/16 pytest100% offline.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P1-U06, R28 + AIDE 1 R27)#
Nội dung Gốc (02-track-edai-raw-curriculum.md, R28 & AIDE 1 R27) |
Nâng cấp Chuẩn SOTA 2026 (ch-06) |
Mục trong Chương 06 | Tạo tác & Kiểm thử (container_ops_lab) |
|---|---|---|---|
1. Introduction to VM and containers (R28, R27) |
Type-1/Type-2 Hypervisor vs. Container dùng chung nhân vs. Firecracker microVM (KVM, <5 MiB, <=125 ms); 7 Linux Namespaces (PID, NET+veth, MNT+pivot_root, UTS, IPC, USER+subuid, CGROUP); cgroups v2 (cpu.max, memory.high/max 137, pids.max, io.max); OverlayFS (lowerdir/upperdir/.wh.*, 2W) |
Trụ cột 1 (§1.1–§1.4) + Mermaid 1 + Widget 1 | linux_isolation_sim.py (evaluate_namespace_isolation, simulate_cgroups_v2_throttling_and_oom, simulate_overlayfs_cow_and_whiteouts), Tests 01, 02, 03 |
2. Docker & architecture design (R28, R27) |
Chuỗi docker CLI -> dockerd -> containerd -> shim -> runc; lỗ hổng /var/run/docker.sock; 3 chuẩn OCI v1.1 (Image DiffID/ChainID, Runtime config.json, Distribution /v2/+Referrers); động cơ BuildKit LLB DAG & --mount=type=cache/bind/secret |
Trụ cột 1 (§1.5) + Trụ cột 2 (§2.1–§2.2) + Trụ cột 3 (Cases 4, 5) + Mermaid 1, 2 | linux_isolation_sim.py (simulate_buildkit_layer_cache), Dockerfile, Dockerfile.naive, Tests 04, 06, 07 |
3. Understand different containerization technologies (R28, R27: Docker vs. Podman) |
Đối chiếu Docker daemon rootful (runc) với Rootless Podman không daemon (fork-exec -> conmon -> crun, CLONE_NEWUSER subuid/subgid, fuse-overlayfs/userxattr, pasta) và Firecracker sandbox AI |
Trụ cột 1 (§1.5) + Trụ cột 2 (§2.1) + Trụ cột 3 (Playbook A) | linux_isolation_sim.py (evaluate_namespace_isolation), Test 01 |
4. Docker commands (R28, R27) |
Vòng đời lệnh CLI (build, tag, push/pull, run với --read-only --cap-drop=ALL --cpus --memory --pids-limit, ps, logs, inspect, stats, exec, stop 143 vs 137, rm, system df, system prune) & nsenter gỡ lỗi distroless |
Trụ cột 1 (§1.6) + Trụ cột 3 (Case 3 + Playbook B) | README.md CLI runbook, Dockerfile (STOPSIGNAL SIGTERM, exec-form CMD), Test 07 |
5. Docker volumes and network (R28, R27) |
Lưu trữ (Named Volume vs Bind Mount vs tmpfs, /dev/shm 64 MiB PyTorch); Mạng (bridge mặc định vs tự định nghĩa, host, none, overlay VXLAN 4789, DNS nhúng 127.0.0.11, mạng kép frontend + internal: true backend) |
Trụ cột 1 (§1.7) + Trụ cột 2 (§2.3) + Trụ cột 3 (Cases 2, 6 + Playbook C) + Mermaid 3 + Widget 3 | docker-compose.yml (pgdata, tmpfs, frontend + internal: true backend), container_audit_and_compose.py (analyze_compose_stack), Tests 09, 10 |
6. Private Artifact Registry (R28, R27) |
Khử trùng lặp theo nội dung sha256 (HEAD /v2/.../blobs/<digest>), Harbor (pull-through cache, Trivy scan-on-push, khóa tag bất biến), GCP Artifact Registry & Binary Authorization, :latest split-brain vs ghim @sha256: |
Trụ cột 1 (§1.8) + Trụ cột 2 (§2.2) + Trụ cột 3 (Case 5) + Widget 2 | linux_isolation_sim.py (simulate_oci_registry_deduplication), Dockerfile digest audit, Tests 05, 06 |
7. Docker Compose (R28, R27) |
Đặc tả Compose (v2 \(\to\) v5), depends_on: condition: service_healthy sắp xếp DAG, profiles, secrets (/run/secrets/), deploy.resources.limits/mem_limit/cpus, develop.watch (sync/rebuild) |
Trụ cột 1 (§1.9) + Trụ cột 2 (§2.3) + Mermaid 3 + Widget 3 | docker-compose.yml, container_audit_and_compose.py, Tests 08, 09, 10 |
8. Comprehensive guideline to build, run, optimize and manage containers (R28, R27) |
Đa tầng vs Distroless vs Chainguard Wolfi (glibc) vs bẫy Alpine musl (PEP 600 vs PEP 656); uv tách uv.lock + .dockerignore; USER >= 10001, --read-only, --cap-drop=ALL, no-new-privileges, seccomp; SBOM (SPDX 3.0/CycloneDX 1.6), Trivy/Grype, Cosign v3.0/SLSA v1.1 |
Trụ cột 2 (§2.2) + Trụ cột 3 (Cases 1–5 + Playbooks A–C) + Mermaid 2 + Widget 2 | Dockerfile vs Dockerfile.naive, .dockerignore, audit_dockerfile, Tests 06, 07 |
9. Lab: Dockerize API + Compose + Container-based Application Testing (R28, R27) |
Đóng gói dịch vụ FastAPI + PostgreSQL + Redis trên Compose và kiểm thử tích hợp không đụng độ bằng Testcontainers (cổng host động + WaitStrategy + Ryuk), kết hợp kiểm định offline PyYAML + httpx.ASGITransport |
Trụ cột 1 (§1.9) + Trụ cột 2 (§2.3) + Trụ cột 3 (Case 6) + Trụ cột 4 (§4.1–§4.3) | app.py, docker-compose.yml, testcontainers_reference/test_containers_e2e.py, run_lab_demo.py, Tests 11–16 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 06 (Unified Notation)#
| Ký hiệu | Miền / Kiểu | Định nghĩa Chính xác Trong Chương 06 & container_ops_lab |
Quy ước Phân biệt |
|---|---|---|---|
| \(Q_{\text{cpu}}, P_{\text{cfs}}\) | \(\mathbb{R}_+\) (\(\mu\text{s}\) / ms) |
Hạn ngạch CPU tổng ($MAX trong cpu.max) và chu kỳ điều tiết mặc định (`\(PERIOD = 100,000\;\mu\text{s} = 100\text{ ms}\)) |
Trần vCPU hiệu dụng \(= Q_{\text{cpu}} / P_{\text{cfs}}\) |
| \(N_{\text{thr}}, N_{\text{core}}\) | \(\mathbb{N}_+\) | Số luồng chạy song song trong container (OMP_NUM_THREADS) và số lõi vật lý máy chủ (os.cpu_count()) |
Khi không ghim, \(N_{\text{thr}}\) thường tự đặt bằng \(N_{\text{core}}\) |
| \(t_{\text{exhaust}}, t_{\text{stall}}\) | \(\mathbb{R}_{\ge 0}\) (ms) |
Thời gian \(N_{\text{thr}}\) đốt hết ngân sách \(Q_{\text{cpu}}\) (\(Q_{\text{cpu}}/N_{\text{thr}}\)) và khoảng thời gian bị nhân Linux treo cứng phần còn lại của \(P_{\text{cfs}}\) | Tỷ lệ điều tiết \(= \text{nr\_throttled} / \text{nr\_periods}\) |
| \(M_{\text{high}}, M_{\text{max}}\) | \(\mathbb{R}_+\) (MiB) |
Ngưỡng kích hoạt thu hồi trang nhớ mềm (memory.high) và trần cứng kích hoạt OOM killer (memory.max \(\to\) Exit 137) |
Phân biệt Exit 137 (128+9 SIGKILL) với 143 (128+15 SIGTERM) |
| \(W, \text{Size}_{\text{img}}\) | \(\mathbb{R}_+\) (MB/GiB) |
Kích thước tệp trọng số/thư viện trong lowerdir và tổng kích thước phân phối của ảnh OCI qua các lớp OverlayFS |
Chỉnh inode chmod/chown ở RUN riêng tạo ảnh \(\ge 2W\) |
| \(D_{\text{hit}}, B_{\text{dedup}}\) | \([0, 1]\), MB |
Tỷ lệ trúng bộ nhớ đệm lớp BuildKit và dung lượng tiết kiệm nhờ khử trùng lặp sha256 trên Private Registry |
Kiểm định khử trùng lặp theo digest, độc lập với tên tag |
| \(S_{\text{sec}}\) | \([0, 100]\) | Điểm kiểm toán tự động Dockerfile và cấu trúc mạng/bảo mật docker-compose.yml trong container_audit_and_compose.py |
Dockerfile chuẩn đạt 100/100 (HARDENED) |
Trụ cột 1 — Nguyên lý Gốc: Ảo hóa Tầng nhân, 7 Namespaces, cgroups v2, OverlayFS, OCI v1.1, Docker vs. Podman & Compose#
1.1 Máy ảo (Hypervisor Type-1/2) vs. Linux Container & Cầu nối Firecracker microVM#
Sự khác biệt cốt lõi giữa máy ảo (Virtual Machine — VM) và container nằm ở vị trí ranh giới ảo hóa: VM ảo hóa phần cứng để chạy một nhân hệ điều hành khách (guest kernel) riêng biệt, còn container chia sẻ trực tiếp nhân Linux của máy chủ (host kernel) và dùng cơ chế phân vùng của chính nhân đó để cô lập tiến trình.
| Tiêu chí Kỹ thuật | VM Type-1 (Bare-Metal Hypervisor) | VM Type-2 (Hosted Hypervisor) | Linux Container (OS-Level Isolation) |
Firecracker microVM (KVM Bridge) |
|---|---|---|---|---|
| Ví dụ Điển hình | Linux KVM, Xen, VMware ESXi, Hyper-V | VirtualBox, VMware Workstation | Docker (runc), Podman (crun), containerd |
Firecracker (VMM viết bằng Rust trên KVM; AWS Lambda & Fargate) |
| Kiến trúc Thực thi | Chạy trực tiếp trên CPU (Intel VT-x / AMD-V Ring -1), cấp phát vCPU, BIOS/UEFI, PCI, NIC ảo |
Chạy như tiến trình người dùng trên hệ điều hành chủ, gián tiếp qua driver OS | Tiến trình người dùng thông thường trên cùng một nhân Linux chủ | VMM Rust tối giản trên /dev/kvm, cắt bỏ BIOS/PCI/USB/VGA; chỉ giữ VirtIO tối thiểu (virtio-net, virtio-block, virtio-vsock) |
| Thời gian Khởi động | ~10–60 giây (BIOS + boot nhân + systemd) |
~20–90 giây |
~10–100 ms (clone() + execve(), 34–48 ms trong Lab 05) |
<= 125 ms (118.0 ms trong Lab 05) |
| Chi phí RAM Nền | ~256 MiB – nhiều GiB cho mỗi nhân khách |
~512 MiB – nhiều GiB |
~1–10 MiB (2.8–6.5 MiB shim/conmon) |
< 5 MiB (4.5 MiB overhead cho mỗi VMM) |
| Ranh giới Bảo mật | Cô lập phần cứng (EPT/NPT bảng trang nhớ + IOMMU) | Phần cứng + tầng OS chủ | Cô lập phần mềm chia sẻ ~300+ syscalls của nhân chủ |
Cô lập phần cứng KVM + lớp jailer (chroot, cgroups, seccomp) |
Tại sao Container Thuần Không Đủ An toàn Cho Sandbox Chạy Mã AI Đa người thuê?
Khi xây dựng hệ thống Code Interpreter cho Agent AI (thực thi mã Python bất kỳ do LLM sinh ra) hoặc nền tảng chạy mô hình đa khách hàng, toàn bộ container trên cùng một máy chủ vật lý đều gọi trực tiếp tới cùng một nhân Linux (~300+ syscalls, io_uring, eBPF, netfilter, VFS). Chỉ cần một lỗ hổng leo thang đặc quyền trong nhân (Dirty COW, Dirty Pipe) là mã độc trong container có thể thoát ra quyền root máy chủ và đọc bộ nhớ mọi khách hàng khác. Đó là lý do các hạ tầng AI hiện đại dùng Firecracker microVM làm cầu nối: đạt mật độ và tốc độ gần ngang container (< 5 MiB, <= 125 ms) nhưng giữ nguyên ranh giới phần cứng KVM (bề mặt chia sẻ rút về vài chục điểm cuối tối giản).
1.2 Bảy Không gian Tên Nhân Linux (7 Kernel Namespaces) & Cơ chế Thoát chroot vs. pivot_root#
Dưới góc nhìn của nhân Linux, không hề tồn tại khái niệm "vật thể container"; container chỉ là tập hợp các tiến trình Linux bình thường được khởi tạo qua các lời gọi hệ thống clone(2), unshare(2), và setns(2) để thu hẹp tầm nhìn tài nguyên toàn cục:
| Namespace | Cờ clone(2) |
Phiên bản Nhân | Tệp /proc/<pid>/ns/* |
Tài nguyên Cô lập & Cơ chế Nội tại Sống còn |
|---|---|---|---|---|
PID |
CLONE_NEWPID |
Linux 2.6.24 |
pid |
Cấp cây phân cấp PID riêng: tiến trình đầu tiên bên trong nhận PID 1 (gánh trách nhiệm xử lý SIGTERM và thu hồi tiến trình con mồ côi zombie qua waitpid()), trong khi trên máy chủ nó vẫn mang một PID thực (ví dụ 48219). Cần mount lại /proc trong MNT ns để ps/top chỉ thấy PID nội bộ. |
NET |
CLONE_NEWNET |
Linux 2.6.29 |
net |
Tách rời giao diện mạng (lo, eth0), ngăn xếp IPv4/IPv6, bảng định tuyến, không gian cổng 0–65535, /proc/net và quy tắc iptables/nftables. Giao tiếp ra ngoài qua cặp veth (Virtual Ethernet): một đầu nằm trong container (eth0), đầu kia cắm vào cầu L2 (docker0 / br-*) nối NAT/MASQUERADE. |
MNT |
CLONE_NEWNS |
Linux 2.4.19 |
mnt |
Cô lập bảng điểm gắn kết tệp (/proc/<pid>/mounts). Các engine OCI dùng pivot_root(new_root, put_old) để tách gốc hệ thống tệp, không dùng chroot. |
UTS |
CLONE_NEWUTS |
Linux 2.6.19 |
uts |
Cô lập nodename (hostname riêng của container) và domainname (sethostname(2)). |
IPC |
CLONE_NEWIPC |
Linux 2.6.19 |
ipc |
Tách hàng đợi thông điệp, semaphore System V và bộ nhớ chia sẻ POSIX (/dev/mqueue, /dev/shm). Chú ý: Docker mặc định giới hạn /dev/shm ở 64 MiB, dễ làm chết worker PyTorch DataLoader bằng SIGBUS! |
USER |
CLONE_NEWUSER |
Linux 3.8 |
user |
Ánh xạ UID/GID và quyền Linux Capabilities bên trong sang UID/GID không có đặc quyền trên máy chủ qua /proc/<pid>/uid_map và gid_map (<inside> <outside> <count>), dựa trên /etc/subuid và /etc/subgid (ví dụ appuser:100000:65536). Nhờ vậy UID 0 (root) trong container ánh xạ thành UID 100000 vô hại ở ngoài host! |
CGROUP |
CLONE_NEWCGROUP |
Linux 4.6 |
cgroup |
Ảo hóa góc nhìn cây /proc/<pid>/cgroup và /sys/fs/cgroup để container thấy nhánh cgroup của mình như gốc / mà không lộ đường dẫn slice máy chủ. |
(Thứ 8: TIME) |
CLONE_NEWTIME |
Linux 5.6 |
time |
Cô lập độ lệch CLOCK_MONOTONIC và CLOCK_BOOTTIME (phục vụ lưu/phục hồi trạng thái CRIU, chưa bật mặc định trong OCI container chuẩn). |
Vì sao pivot_root Chặn Đứng Lỗ hổng Thoát chroot & Cách Gỡ lỗi Container Không Có Shell Bằng nsenter?#
- Lỗ hổng Thoát
chroot: Lời gọichroot(path)(CAP_SYS_CHROOT) chỉ đổi con trỏ tra cứu/của tiến trình mà vẫn giữ nguyên cây gắn kết máy chủ và các bộ mô tả tệp (file descriptor —fd) đang mở từ trước. Một tiến trình cóCAP_SYS_CHROOThoặc giữ mộtfdthư mục nằm ngoài nhà tù chỉ cần tạomkdir("sub"), gọichroot("sub"), gọifchdir(fd)rồi lặpchdir("..")là vượt qua khỏi ranh giới gốc về thẳng/thật của máy chủ! - Tính Bất khả xâm phạm của
pivot_root(new_root, put_old): Đòi hỏinew_rootlà một điểm gắn kết (mount point) thực thụ và hoán đổi nguyên tử thư mục gốc/củaMNTnamespace sangnew_root, đẩy gốc cũ của máy chủ vàoput_old. Ngay lập tức sau đó, runtimerunc/crunthực thiumount2(put_old, MNT_DETACH)và xóaput_old— cắt đứt vĩnh viễn mọi liên kết tới cây thư mục máy chủ. - Quan sát từ
/proc&nsenter: Từ máy chủ Linux, quản trị viên vẫn nhìn thấy tiến trình container trongps auxvà đối chiếu từng inode tại/proc/<host_pid>/ns/*(hai tiến trình chung namespace khi và chỉ khi mã inode khớp nhau). Khi container dùng ảnh tối giản Distroless/Wolfi không chứa/bin/sh, kỹ sư hạ tầng vẫn gắn công cụ gỡ lỗi từ máy chủ vào đúng không gian mạng/tiến trình của container qua lệnhnsenter --target <host_pid> --net --pid!
1.3 Phân cấp Thống nhất cgroups v2: Điều tiết CPU (cpu.max), Ngưỡng RAM (memory.high vs. memory.max \(\to\) Exit 137) & pids.max#
Nếu Namespaces quyết định container nhìn thấy những gì, thì cgroups v2 (Control Groups phiên bản 2) quyết định container được phép tiêu thụ bao nhiêu tài nguyên vật lý. Khác với cgroups v1 phân mảnh thành nhiều cây rời rạc dễ xung đột bộ điều khiển (ví dụ ghi đệm trang nhớ không tính vào giới hạn I/O blkio), cgroups v2 hợp nhất thành một cây phân cấp duy nhất tại /sys/fs/cgroup/, điều phối qua cgroup.controllers, cgroup.subtree_control (+cpu +memory +io +pids) và cgroup.procs (chỉ đặt tiến trình ở các nút lá theo quy tắc No Internal Process Constraint).
1.3.1 Toán học Điều tiết Băng thông CFS (cpu.max & cpu.stat) và Bẫy Giật p99 Trên Python/ML#
Tệp /sys/fs/cgroup/.../cpu.max ghi cặp giá trị "$MAX $PERIOD" theo đơn vị micro-giây (\(\mu\text{s}\)), với chu kỳ mặc định \(P_{\text{cfs}} = 100,000\;\mu\text{s} = 100\text{ ms}\) (đặt $MAX = "max" để gỡ trần):
Điểm chí tử ít kỹ sư để ý là: ngân sách \(Q_{\text{cpu}}\) là quỹ thời gian CPU cộng dồn cho toàn bộ mọi luồng chạy đồng thời trong cgroup trên mỗi cửa sổ \(P_{\text{cfs}}\). Khi có \(N_{\text{thr}}\) luồng đồng thời tranh CPU trên máy chủ \(N_{\text{core}}\) lõi:
Hệ quả trên hệ thống AI/ML: Các thư viện PyTorch, NumPy/OpenBLAS/MKL, hay máy chủ web nhiều worker kiểm tra os.cpu_count() của máy chủ vật lý (16–64 lõi) thay vì hạn mức cgroup. Với cpu.max = "100000 100000" (1.0 vCPU), nếu chạy 16 luồng song song, toàn bộ 100 ms ngân sách bị đốt sạch chỉ trong t_exhaust = 100 / 16 = 6.25 ms, và nhân Linux ép cả 16 luồng ngủ đông cứng suốt t_stall = 93.75 ms còn lại! Trong thực nghiệm Lab 05 (simulate_cgroups_v2_throttling_and_oom), việc không ghim luồng đã tạo ra tỷ lệ điều tiết 24.53% (13/53 chu kỳ, tổng 1,263,444 \(\mu\text{s}\) bị treo) và kéo p99 vọt 10.94x (16.1 ms -> 176.08 ms). Kỹ sư phải theo dõi nr_throttled / nr_periods và throttled_usec trong cpu.stat, ghim cứng OMP_NUM_THREADS/MKL_NUM_THREADS theo vCPU, hoặc dùng cpu.weight / ghim lõi cpuset tĩnh cho cụm suy luận nhạy độ trễ.
1.3.2 Phân biệt memory.high, memory.max & Giải phẫu Mã thoát Exit Code 137#
memory.high(Ngưỡng Phanh Mềm): Khi RAM vượt quá \(M_{\text{high}}\) (420 MiBtrong Lab 05), nhân Linux không giết tiến trình mà ép thu hồi trang nhớ trực tiếp (direct reclaim) và làm chậm luồng cấp phát bộ nhớ — gây trễp50/p99tăng vọt nhưng cho phép ứng dụng xả bớt bộ nhớ đệm để sống sót.memory.max(Trần Cứng \(\to\) OOM Killer \(\to\)Exit Code 137): Khi bộ nhớ không thể thu hồi (heap ẩn của Python, tensor PyTorch, vùng nhớ dirty) chạm \(M_{\text{max}}\) (512 MiB), bộ đếmoomvàoom_killtrongmemory.eventstăng lên, và nhân kích hoạt OOM Killer bắn tín hiệuSIGKILL(số hiệu9) không thể chặn hay bắt lấy:\[\text{Mã thoát Container} = 128 + \text{Số hiệu Tín hiệu} = 128 + 9\;(\text{SIGKILL}) = \mathbf{137}\]Để phân biệt OOM Kill với việc bị người dùng/Kubelet bắnSIGKILL, luôn kiểm tradocker inspect <id> --format='{{.State.OOMKilled}}'và log nhândmesg -T | grep -i oom.
1.3.3 Bảo vệ Chống Bom Tiến trình (pids.max) & Băng thông Đĩa (io.max)#
pids.max: Chốt chặn tổng số tiến trình và luồng đồng thời; khipids.current == pids.max, mọi lệnhfork()/clone()mới lập tức trả lỗi-EAGAIN, chặn đứng bom tiến trình (:(){ :|:& };:) hoặc rò rỉ luồng PyTorch làm sập bảng PID máy chủ.io.max: Giới hạn băng thông (rbps/wbpsbyte/s) và IOPS (riops/wiops) theo từng thiết bị khối<major>:<minor>, ngăn tiến trình ghi checkpoint mô hình khổng lồ bóp nghẹt ổ NVMe của các pod láng giềng.
1.4 Hệ thống Tệp Hợp nhất OverlayFS & Chứng minh Biểu thức Phình 2W#
Một Docker/OCI Image không phải một tệp ảnh đĩa nguyên khối mà là chồng các lớp tar chỉ đọc xếp chồng lên nhau thông qua OverlayFS:
lowerdir: Danh sách bất biến các lớp ảnh chỉ đọc từ dưới lên (lowerdir=L_n:...:L_1:L_0).upperdir: Duy nhất một lớp cho phép ghi nằm trên cùng, lưu mọi chỉnh sửa và xóa tệp trong quá trình chạy container (hoặc khi tạo một lớpRUNmới lúc build).workdir: Thư mục đệm rỗng nằm trên cùng phân vùng tệp vớiupperdir, giúp nhân thực hiện thao tác đổi tên nguyên tử (atomic rename) tránh hỏng dữ liệu nếu mất điện giữa chừng khi đangcopy-up.merged: Khung nhìn hợp nhất mà tiến trình bên trong container nhìn thấy tại/.
Chứng minh Hình thức Vì sao RUN chmod/chown Ở Bước Riêng Nhân Đôi Trọng số (2W) & Vì sao RUN rm Không Giảm Dung lượng Ảnh#
Giả sử bước \(L_1\) chép tệp trọng số model.safetensors kích thước \(W\) byte (800 MB), rồi bước \(L_2\) thực thi RUN chmod 0644 /models/model.safetensors && chown 10001:10001 /models/model.safetensors:
- Lớp \(L_1\) tạo tệp trong
upperdirtrống và đóng băng thành lớp bất biến có dung lượng \(\text{Size}(L_1) = W\). - Khi chạy
RUN chmod/chownở \(L_2\), tệp đích nằm tronglowerdirchỉ đọc (\(L_1\)). Theo nguyên tắc Copy-on-Write mức tệp (file-granularitycopy-up) của OverlayFS, bất kỳ thay đổi nào — dù chỉ đổi vài bit quyềnst_modehayst_uidtrong inode — đều buộc nhân sao chép toàn bộ \(W\) byte của tệp quaworkdirlênupperdircủa \(L_2\) rồi mới sửa thuộc tính. - Vì mỗi lớp OCI lưu trữ ảnh chụp toàn tệp của
upperdirchứ không lưu vá nhị phân siêu dữ liệu, \(\text{Size}(L_2) = W\). - Nếu ở bước \(L_3\) ta chạy
RUN rm -f /models/model.safetensors, \(L_1\) và \(L_2\) vẫn bất biến: OverlayFS chỉ tạo một tệp đánh dấu whiteout0 bytetên/models/.wh.model.safetensors(hoặc thiết bị ký tực 0, 0trong kernel live /.wh..wh..opqvàtrusted.overlay.opaque="y"khi xóa cả thư mục) để che tệp đó khỏi góc nhìnmerged. Tổng dung lượng ảnh OCI phân phối qua mạng là:
Trong Lab 05 (test_03), kích thước ảnh với trọng số 800 MB nhảy từ 920 MB lên 1,720 MB (và vẫn là 1,720.01 MB sau RUN rm dù merged chỉ còn thấy 120 MB!). Khắc phục dứt điểm bằng cách dùng COPY --chmod=0644 --chown=10001:10001 hoặc gói chung vào một câu lệnh RUN duy nhất hoặc sao chép qua giai đoạn build đa tầng (multi-stage).
1.5 Chuẩn OCI v1.1, Kiến trúc Docker vs. Rootless Podman & BuildKit DAG#
Ba Đặc tả Cốt lõi của Open Container Initiative (OCI v1.1)#
OCI Image Spec v1.1: Chuẩn hóa cấu trúc bất biến định danh bằng hàm bămsha256: Image Index (index.v1+json, ánh xạ đa kiến trúcamd64/arm64), Image Manifest (manifest.v1+json, trỏ tớiconfig, mảng lớp néngzip/zstd, và trườngsubjectv1.1 đính kèm SBOM/chữ ký), và Image Config JSON chứarootfs.diff_ids(SHA-256 của từng lớp tar chưa nén). Chuỗi phả hệ lớp được khóa toàn vẹn bằngChainID:\[\text{ChainID}(L_0) = \text{DiffID}(L_0), \qquad \text{ChainID}(L_0 \mid \dots \mid L_i) = \text{sha256}\Big(\text{ChainID}(L_0 \mid \dots \mid L_{i-1}) \parallel \text{" "} \parallel \text{DiffID}(L_i)\Big)\]OCI Runtime Spec v1.1: Mô tả gói thực thi gồm thư mụcrootfs/và tệpconfig.json(quy định namespaces, cgroups, capabilities, seccomp, mounts, user) để runtime cấp thấp (runcbằng Go hoặccrunbằng C) thực thi.OCI Distribution Spec v1.1: Chuẩn hóa giao thức HTTP/v2/giữa client và registry (manifests/<ref>,blobs/<digest>dùngHEADđể bỏ qua bước tải lớp trùngsha256, vàGET /v2/<name>/referrers/<digest>tra cứu SBOM/chữ ký mà không làm rác danh sách tag).
Đối chiếu Kiến trúc Docker Engine (rootful) vs. Rootless Podman (daemonless fork-exec)#
- Docker Engine (
23–29): Vận hành theo mô hình Client–Server qua daemon nền chạy quyềnroot:docker CLI -> REST (/var/run/docker.sock) -> dockerd -> containerd -> containerd-shim-runc-v2 -> runc -> ContainerMỗi container có mộtcontainerd-shimtách rời vòng đời đểdockerd/containerdnâng cấp mà không giết container đang chạy. Tuy nhiên, ai chạm được/var/run/docker.sockđều nắm quyềnroottuyệt đối trên máy chủ (Lab 05test_01:docker_sock_host_root_risk=True,container_uid0_mapped_to_host_uid=0). - Rootless
Podman(v5.x): Vận hành theo mô hình Không Daemon (fork-exec):podman CLI -> fork-exec -> conmon -> crun -> ContainerKhông có dịch vụ nền chạy quyềnroot(quản lý dịch vụ bền vững quasystemdQuadlets). Tiến trình giám sátconmongiữ stdio và mã thoát; runtime Ccrunkhởi động nhanh hơn (34.0 ms,2.8 MiBtrong Lab 05 so với48.0 ms,6.5 MiBcủadockerd+runc). Toàn bộ chạy không cầnrootnhờCLONE_NEWUSER(/etc/subuidánh xạUID 0trong container \(\to\)UID 100000ngoài host), hệ thống tệpfuse-overlayfs(hoặc nhân OverlayFSuserxattrtừ Linux5.11+), và ngăn xếp mạng người dùngpasta(mặc định từ Podman5.0, thayslirp4netnsgiảm trễ rõ rệt).
1.6 Vòng đời Quản trị Lệnh Docker CLI Chuẩn Sản xuất#
- Build & Registry:
docker buildx build --target runtime -t reg/app:v1 .,docker tag,docker push/docker pull. - Run Bảo mật:
docker run -d --name api --cpus=1.0 --memory=512m --pids-limit=256 --read-only --tmpfs /tmp:rw,noexec,nosuid,size=64m --cap-drop=ALL --security-opt=no-new-privileges:true -p 127.0.0.1:8000:8000 <img@sha256:...> - Quan sát:
docker ps -a,docker logs -f --tail 100 api,docker inspect api --format='{{.State.OOMKilled}} {{.State.ExitCode}}',docker stats. - Gỡ lỗi & Dọn dẹp:
docker exec -it api /bin/sh(dùngnsenterkhi ảnh là Distroless/Wolfi),docker stop api(SIGTERM\(\to\)10s\(\to\)SIGKILL),docker rm,docker system df -v,docker system prune -a.
1.7 Lưu trữ (Named Volumes, Bind Mounts, tmpfs) & Mạng (bridge, 127.0.0.11, internal: true)#
| Cơ chế Lưu trữ | Cơ chế Tầng nhân & Vị trí | Tính Bền vững | Dùng Chuẩn & Lưu ý |
|---|---|---|---|
Named Volume (pgdata:/var/lib/...) |
/var/lib/docker/volumes/<tên>/_data; tự mồi dữ liệu lần đầu |
Sống sót qua docker rm / compose down |
DB (Postgres, Qdrant), cache trọng số. Sao lưu qua container phụ xuất tar. |
Bind Mount (./src:/app/src:ro) |
mount --bind trực tiếp đường dẫn máy chủ vào MNT ns |
Gắn chặt đường dẫn & UID/GID máy chủ | Hot-reload dev hoặc tệp cấu hình :ro. Tránh lệch UID ghi tệp root ra host. |
tmpfs (--tmpfs /tmp:rw,noexec,nosuid,size=64m) |
RAM thuần (mount -t tmpfs), không ghi đĩa OverlayFS |
Mất sạch khi container dừng | Vùng /tmp khi --read-only, khóa bí mật runtime. Với PyTorch cần --shm-size=8g. |
- Bốn Driver Mạng & DNS
127.0.0.11:bridgemặc định (docker0) không có DNS theo tên container, bắt buộc dùng User-Defined Bridge (Compose mặc định) cung cấp cô lập L2 và DNS nhúng127.0.0.11(chuyển tiếp quaiptablesDNAT tớidockerd, phân giảipostgres:5432,redis:6379);hostchia sẻ card mạng máy chủ (mất cô lập cổng);nonechỉ giữ loopbacklo(127.0.0.1);overlayđóng gói VXLAN (UDP4789). - Mạng kép
frontend+internal: true backend: Trong Lab 05,apinối cảfrontendvàbackend, cònpostgresvàredischỉ nốibackend(internal: true,0host ports). Cờinternal: truegỡ default gateway và chặn NAT ra WAN, vô hiệu hóa kết nối reverse shell hay tuồn dữ liệu ra ngoài.
1.8 Private Artifact Registry (Harbor, GCP Artifact Registry), Khử Trùng lặp sha256 & Ghim @sha256:#
- Khử Trùng lặp
sha256(/v2/<repo>/blobs/<digest>): Trước khi tải lớp nặng1,150 MB(PyTorch+CUDA), client gửiHEAD: nếu digest đã có trên registry ở bất kỳ tag nào, bước truyền mạng được bỏ qua. Trong Lab 05 (test_05,6tag), tổng thô7,461 MBgiảm xuống còn1,286 MBduy nhất (-82.76%), bỏ qua10/18lượt tải dư thừa. Harbor&GCP Artifact Registry:Harbor(CNCF Graduated) cung cấp Proxy Cache tránh giới hạn Docker Hub, quétTrivyScan-on-Push chặn kéo ảnh lỗi, Tag Immutability khóa ghi đè, và nhân bản đa vùng;GARcung cấp Remote/Virtual Repositories, Artifact Analysis và kiểm soát triển khai GKE qua Binary Authorization.- Tag
:latest(Split-Brain) vs.@sha256:: Dùng:latestcùngimagePullPolicy: IfNotPresentkhiến nút cũ chạy v1 trong khi nút mới kéo v2 gây lệch schema. Phải ghim@sha256:<64-hex>cả trongFROMlẫn manifest K8s.
1.9 Docker Compose (v2 \(\to\) v5) & Kiểm thử Tích hợp Với Testcontainers#
Docker Compose (chuẩn compose.yaml bỏ version:; CLI v2 tiến hóa thẳng lên v5.x cuối 2025 giữ nguyên Compose Spec) điều phối đa dịch vụ:
depends_on+healthcheck: Không dùngdepends_on: [postgres](service_started) mà dùngcondition: service_healthy(pg_isready,redis-cli ping) hoặcservice_completed_successfully(migration), tạo DAG khởi độngpostgres -> redis -> api.profiles,secrets,deploy.resources.limits&develop.watch: Tách dịch vụ phụ bằngprofiles, gắn bí mật tại/run/secrets/, giới hạncpus/memory, và dùngdevelop.watch(sync,sync+restart,rebuild) thay bind mount chậm trên Windows/macOS.Testcontainers(4.x) vs. DB Chung Trên CI: Gán cổng host động ngẫu nhiên (.with_exposed_ports(5432)\(\to\).get_exposed_port(5432)) giúppytest -n autochạy song song 0 đụng độ cổng; đồng bộ quaLogMessageWaitStrategy/HttpWaitStrategy; và dùng sidecarRyuk(TCP heartbeat) xóa sạch 100% container/volume kể cả khi runner nhậnSIGKILL.
Trụ cột 2 — Kiến trúc Hệ thống Sản xuất & Đổi mới SOTA 2024–2026#
2.1 Kiến trúc Cô lập Runtime, cgroups v2 & Ranh giới An toàn AI#
Sơ đồ dưới đây đối chiếu luồng thực thi từ nhân Linux xuống ba mô hình chạy container và microVM phổ biến trong hạ tầng AI hiện đại:
Ngân sách Tài nguyên & Tham số Chống Sập cgroups v2 Cho Dịch vụ AI/FastAPI#
| Thành phần Kiểm soát | Ngưỡng Cấu hình Khuyến nghị 2026 | Cơ chế Sự cố Nếu Bỏ qua | Lệnh / Đường dẫn Giám sát Nhân |
|---|---|---|---|
| CPU Quota & Luồng | Đặt OMP_NUM_THREADS = MKL_NUM_THREADS = TORCH_NUM_THREADS \(\le \lceil Q_{\text{cpu}} / P_{\text{cfs}} \rceil\); dịch vụ nhạy p99 dùng requests.cpu (cpu.weight) hoặc cpuset tĩnh |
16 luồng đốt cạn 100 ms trong 6.25 ms \(\to\) treo 93.75 ms, p99 vọt 10.94x (16.1 -> 176.08 ms) |
/sys/fs/cgroup/cpu.stat (nr_throttled / nr_periods < 5%, throttled_usec) |
Memory & /dev/shm |
Đặt memory.high \(\approx 0.85 \cdot M_{\text{max}}\); mở rộng --shm-size=8g (shm_size / K8s RAM emptyDir); cấu hình MALLOC_MMAP_THRESHOLD_=65536 |
Vượt 64 MiB /dev/shm gây SIGBUS; rò rỉ arena glibc chạm memory.max gây OOM Exit 137 |
/sys/fs/cgroup/memory.events (oom_kill), docker inspect .State.OOMKilled |
| PID 1 & Tín hiệu Tắt | Luôn dùng exec-form CMD ["uvicorn", ...] + STOPSIGNAL SIGTERM + init: true (tini) + preStop: sleep 10 trên K8s |
Shell-form /bin/sh -c nuốt SIGTERM \(\to\) SIGKILL Exit 137 sau 10–30s + lỗi 502 lúc rolling update |
Trạng thái thoát container chuẩn phải là Exit Code 143 (128 + 15) |
2.2 Quy trình Build BuildKit DAG, Tối ưu uv, Ảnh Wolfi/Distroless & Chuỗi cung ứng Cosign#
Một chuỗi build & phân phối ảnh container chuẩn SOTA 2026 tách bạch hoàn toàn pha biên dịch khỏi pha chạy thực tế, kết hợp kiểm định bảo mật tự động trước khi đẩy lên Private Registry:
Cạm bẫy musl (PEP 656) vs. glibc (PEP 600) & Bảng Chọn Ảnh Nền Python/AI 2026#
Một sai lầm phổ biến là chọn python:3.12-alpine chỉ vì thấy nhỏ (~20 MB nén). Do Alpine dùng musl libc thay vì GNU glibc, các thư viện khoa học dữ liệu (torch, numpy, scipy, polars, pyarrow, cryptography) vốn phát hành wheel nhị phân chuẩn PEP 600 (manylinux / glibc) thường thiếu bản dựng PEP 656 (musllinux). Hậu quả là pip/uv buộc phải biên dịch mã nguồn C/C++/Rust từ đầu (kéo thêm gcc, g++, rust mất 5–15 phút và phình kích thước ảnh), giảm kích thước ngăn xếp luồng mặc định xuống 128 KB gây lỗi phân đoạn đa luồng, và vướng lỗi trễ phân giải DNS ndots:5 trong Kubernetes!
| Ảnh Nền Thực thi | Thư viện C | Dung lượng Nén / Giải nén | Shell / Trình cài gói | Lỗ hổng Trivy Điển hình |
Khuyến nghị Sử dụng 2026 |
|---|---|---|---|---|---|
python:3.12-bookworm |
glibc |
~350–400 MB / ~1.0+ GB |
bash / apt + gcc |
Rất cao (100s–1,000+ CVE) |
Chỉ dùng ở Stage 1 Builder nếu cần biên dịch gói C/C++, cấm đưa ra production. |
python:3.12-slim-bookworm |
glibc |
~50–60 MB / ~150–200 MB |
sh/bash / apt |
Trung bình (~50–150 CVE) |
Lựa chọn cân bằng chuẩn cho Lab 05 (175 MB toàn ngăn xếp), 100% tương thích manylinux. |
python:3.12-alpine |
musl |
~18–25 MB / ~50–65 MB |
ash / apk |
Rất thấp (0–10 CVE) |
CẤM dùng cho Python Data/AI (PyTorch/SciPy thiếu musllinux, biên dịch chậm 10x–50x). |
gcr.io/distroless/cc-debian12 |
glibc |
~12–15 MB / ~32 MB |
0 shell / 0 pkg mgr | Gần bằng 0 |
Chép kèm Python độc lập từ uv + /app/.venv (tránh python3-debian12 vì khóa cứng Python 3.11!). |
cgr.dev/chainguard/python (Wolfi) |
glibc |
~22–28 MB / ~50–60 MB |
0 shell / 0 pkg mgr | 0 CVE (build lại hàng đêm) |
Chuẩn SOTA 2026: giữ nguyên glibc (manylinux) + bề mặt tối giản không shell + UID 65532 + SBOM sẵn. |
Chuỗi Cung ứng Bảo mật (SBOM, Trivy/Grype, Cosign v3.0, SLSA v1.1 & OCI Referrers)#
- Tạo SBOM (
SPDX 3.0/CycloneDX 1.6): Lưu ý lệnhdocker sbomcũ đã bị khai tử; sử dụngsyft,trivy image --format cyclonedx,docker scout sbom, hoặc cờ gốc BuildKit--sbom=true --provenance=mode=max. ChuẩnSPDX 3.0(ISO/IEC 5962, 04/2024) vàCycloneDX 1.6(ECMA-424) hỗ trợ cả hồ sơ AI/ML-BOM và OpenVEX. - Cổng Chặn CVE (
Trivy/Grype): Thực thitrivy image --severity HIGH,CRITICAL --exit-code 1 --ignore-unfixed <image@sha256:...>hoặc quét trực tiếp từ tệp SBOM quagrype sbom:sbom.cdx.json --fail-on hightrước khi ký phát hành. - Ký Không Khóa
Cosign v3.0(10/2025) &SLSA v1.1(04/2025): Không lưu khóa riêng dài hạn trên CI! Runner CI xuất trình OIDC JWT tới Fulcio CA để nhận chứng chỉ ngắn hạn (~10 phút), ký bó Sigstore Bundle (.sigstore.json) trên@sha256:bất biến, ghi vết vào nhật ký Merkle công khai Rekor, và gắn trực tiếp vào manifest ảnh quaOCI 1.1 Referrers API(--registry-referrers-mode=oci-1-1) để Kubernetes admission controller (Kyverno/OPA Gatekeeper/Binary Authorization) kiểm địnhcosign verifytrước khi cấp lịch chạy pod. - Góc nhìn Principal (
SOTA 2025–2026— Principal Industrial Tip #14) — Build Đa tầng Tối giản, Cache BuildKitsharing=locked, Ghim@sha256:Đa kiến trúc & Ngắt Êm Ái K8s (SIGTERM+preStop):- Đánh đổi Kiến trúc
Dockerfile: Chia hai giai đoạnbuilder(kèmuvvàARG TARGETARCH) tách khỏiruntimetối giản (slim-bookwormhoặcChainguard Wolfi) loại bỏ 100% toolchain build khỏi ảnh chạy, đồng thời dùng--mount=type=cache,id=uv-${TARGETARCH},sharing=locked,target=/root/.cache/uvđể tránh hỏng kho wheel hoặc lẫn ABIamd64/arm64khi chạy build ma trận song song trêndocker buildx. Ghim@sha256:trỏ tới OCI Image Index đa kiến trúc (chứ không phải digest riêng lẻ của một nền tảng) để cả CI ARM64 lẫn cụm Kubernetes x86_64 kéo cùng một nguồn bất biến. - Chế độ Lỗi Sản xuất: (1) Không tách
id=uv-${TARGETARCH},sharing=lockedkhiến các build song song ghi đè bộ nhớ đệm wheeluvhoặc kéo nhầm wheel sai kiến trúc; (2) dùng:latestdẫn tới sai lệch phiên bản giữa các node (split-brain); (3) thiếu exec-formCMDkhiến tiến trình shell PID 1 nuốt mấtSIGTERM(làm pod quá hạn grace period và bị kết liễu cưỡng bức vớiExit Code 137—SIGKILL), trong khi thiếuSTOPSIGNAL SIGTERMhoặc hookpreStopdù vẫn thoát êm ởExit Code 143nhưng lại đóng socket trước khikube-proxykịp gỡ IP khỏi EndpointSlice, sinh bão502 Bad Gateway.
- Đánh đổi Kiến trúc
2.3 Kiến trúc Mạng kép Docker Compose, Khởi động Topo service_healthy & Testcontainers#
Sơ đồ dưới đây mô tả đúng cấu trúc chạy thật của docker-compose.yml và testcontainers_reference/test_containers_e2e.py trong Lab 05:
Ba Quy tắc Sắt Cho Docker Compose & Testcontainers Trong Doanh nghiệp#
- Không Phơi Cổng Dữ liệu & Cô lập
internal: true: Trongdocker-compose.ymlchuẩn bảo mật của Lab 05,postgresvàredisgắn duy nhất mạngbackend(internal: true) vớiexposed_host_ports == []. Chỉ cổng dịch vụapiđược gắn cục bộ127.0.0.1:8000:8000qua mạngfrontend. - Kiểm soát Khởi động Topo & Tính Bất biến Hệ thống Tệp: Đồ thị
depends_ondùngcondition: service_healthybuộc thuật toán sắp xếp topo Kahn khởi chạypostgresvàrediskhỏe mạnh hoàn toàn trước khiapimở cổng; bản thân containerapivàrediskhóa cứngread_only: true, cấp vùng ghi tạm giới hạn quatmpfs: [/tmp:rw,noexec,nosuid,nodev,size=64m], tước sạch quyền Linux (cap_drop: [ALL]), khóano-new-privileges:true, và bậtinit: trueđể tránh zombie process. - Ephemeral
TestcontainersCho Kiểm thử Tích hợp Thực thụ: Khi tích hợp CI nhiều nhánh chạy song song, mọi fixture DB/Redis dùngPostgresContainer/RedisContainerđể cấp cổng ngẫu nhiên từ dải ephemeral của hệ điều hành kết hợpLogMessageWaitStrategyvà dọn dẹp tự động bởiRyuk. (Trên các máy trạm Windows không bật Docker daemon, Lab 05 tách riêng tập lệnh kiểm thử thật vàotestcontainers_reference/test_containers_e2e.pyngoàitestpaths = ["tests"]để16/16capytestchạy xác minh chính xácPyYAMLDAG, chính sách bảo mật và ứng dụng FastAPI quahttpx.ASGITransport100% offline).
Trụ cột 3 — Sáu Sự cố Sản xuất Kinh điển, Mã Nguồn Chuẩn Thực thi & Ba Bảng Ra quyết định#
Case 1 — Điều tiết CFS cpu.max Làm Đóng băng Dịch vụ AI Dù CPU Trung bình Chỉ 30% (Indeed #67577 / Omio / Uber)#
- Bối cảnh & Số liệu Thực tế: Trong vụ việc nổi tiếng được Dave Chiluk (Indeed) phân tích (Kubernetes Issue
#67577) và tái hiện tương tự ở Omio (GKE) cùng Uber, các dịch vụ đa luồng chạy sau bộ điều phối bị rớt yêu cầu và tụt đầu dò sức khỏe với độ trễ đuôi> 2,000 ms, dù đồ thị giám sát chỉ báo CPU sử dụng trung bình20%–50%. Sau khi vá lỗi kế toán ngân sách CFS và loại bỏ điều tiết cứng, độ trễ tệ nhất giảm66xxuống30 ms. - Cơ chế Trên Dịch vụ Python/PyTorch: Trên máy chủ
16–64lõi, bộ chạy OpenMP/MKL/PyTorch mặc định mở đủ số luồng theoos.cpu_count()thay vì hạn mức cgroup. Vớicpu.max = "100000 100000",16luồng đốt sạch100 msngân sách chỉ trong6.25 msrồi bị nhân treo cứng93.75 ms(p99trong Lab 05 tăng10.94xtừ16.1 -> 176.08 ms). - Khắc phục: Ghim tường minh
OMP_NUM_THREADS=2,MKL_NUM_THREADS=2trongDockerfile&docker-compose.yml, giám sát tỷ lệnr_throttled / nr_periodstrong/sys/fs/cgroup/cpu.stat, và cân nhắc bỏlimits.cpu(chỉ đặtrequests.cpu) hoặc ghimCPUManagerstatictrên nút suy luận nhạy độ trễ.
Case 2 — Cạn /dev/shm (64 MB) Trên PyTorch DataLoader & Phân mảnh Arena glibc ptmalloc2 Dẫn Tới Exit Code 137#
- Cơ chế Sự cố: (1) Docker mặc định khóa
/dev/shmở64 MiB; khiPyTorch DataLoader(num_workers > 0)trao đổi tensor ảnh/token lớn qua bộ nhớ chia sẻ POSIX, worker lập tức chết vìSIGBUS(Bus error). (2) Khi dùngfork(), các tiến trình con lặp qualist/dictPython thuần làm biến đổi bộ đếm tham chiếuob_refcnt, kích hoạt Copy-on-Write nhân bản RAM lên gấpNlần số worker. (3) Bộ cấp phátglibc ptmalloc2giữ lại các arena riêng cho từng luồng không trả về OS khi cấp xen kẽ tensor lớn và đối tượng Python nhỏ;tracemallocđứng yên nhưng RSS phình dần cho tới khi chạmmemory.maxvà bị OOM Killer giết bằngSIGKILL(Exit Code 137). - Khắc phục: Gắn
--shm-size=8g(shm_sizetrong Compose /emptyDir: { medium: Memory }trong K8s), chuyển chỉ mục dữ liệu sangnp.ndarray/PyArrow không sao chép, thêmENV MALLOC_MMAP_THRESHOLD_=65536 MALLOC_TRIM_THRESHOLD_=65536(hoặc dùnglibjemalloc), và cấu hình tái tạo worker định kỳ (max_requests).
Case 3 — Bẫy PID 1 /bin/sh -c Nuốt SIGTERM (Exit 137 vs. 143) & Lỗi 502 Khi Rolling Update#
- Cơ chế Sự cố: Viết
CMD uvicorn ...dạng shell-form khiến Docker bọc tiến trình dưới/bin/sh -c "uvicorn ...". Trong nhân Linux, tiến trìnhPID 1bỏ qua hành vi mặc định củaSIGTERM, và/bin/shkhông chuyển tiếpSIGTERMxuống tiến trình con. Khi Docker/Kubernetes gửiSIGTERMđể rút pod, pod treo suốt10–30 giâycho đến khi bị ép chết bằngSIGKILL(Exit Code 137). Hơn nữa, ngay cả khi dùng exec-form, Kubernetes gửiSIGTERMsong song với việc cập nhật bảngiptables/EndpointSlice(2–10 giâyđộ trễ lan truyền), nên pod tắt ngay lập tức sẽ gây lỗi502 Bad Gateway. - Khắc phục: Bắt buộc dùng exec-form
CMD ["uvicorn", ...]+STOPSIGNAL SIGTERM+ trình quản trịinit: true(tini/dumb-init) để thu hồi zombie và chuyển tiếp tín hiệu, trả mã thoát chuẩnExit Code 143, kết hợp hookpreStop: sleep 10trước khi bắt đầu tắt.
Case 4 — Rò rỉ Bí mật Trong 7.86 Giây Từ docker history, COPY . Phá Cache & Phình 2W Trên OverlayFS#
- Bằng chứng Thực nghiệm (Stony Brook ACM CCS — Tsouvalas & Nikiforakis): Nhóm nghiên cứu công bố
300ảnh mật bẫy chứa khóa giả trên các registry công khai. Hệ thống quét tự động ("ContainerBots") giải nén từng lớp ảnh và đọcdocker history --no-trunc/ Config JSON mà không cần chạy container: khóa AWS bị khai thác nhanh nhất chỉ sau7.86 giây(trung vị~51 giây,100%khóa AWS bị lạm dụng trong vòng15 phút). Mọi khóa khai báo bằngARG,ENV, hayCOPY .envrồiRUN rmđều lưu vết vĩnh viễn! - Bẫy Hiệu năng Build: Đặt
COPY . /apptrước bước cài thư viện khiến mỗi lần sửa 1 dòng code Python phải kéo lại toàn bộ gói từ mạng (68.3 s/commitvs3.64 s/commitkhi táchuv.lockqua--mount=type=bind+--mount=type=cache, tăng tốc18.76xtrong Lab 05), và táchRUN chmod/chownphía sauCOPYnhân đôi kích thước trọng số thành2W(1,720 MBvs920 MB). - Khắc phục: Dùng
--mount=type=secretcho khóa tạm lúc build, enforce.dockerignore, đặtCOPY --chown=10001:10001, và chạytrivy fs --scanners secretở CI.
Case 5 — Leo thang Quyền /var/run/docker.sock, Bẫy musl Alpine & Trôi Phiên bản :latest Split-Brain#
- Cơ chế Sự cố: (1) Gắn
-v /var/run/docker.sock:/var/run/docker.sockvào runner CI hay agent AI cho phép bất kỳ thư viện PyPI độc hại nào chạydocker run --privileged -v /:/host alpine chroot /host shđể chiếm toàn quyềnrootmáy chủ. (2) Chọnpython:3.12-alpine(musl) làmtorch/numpy/cryptographymất wheelmanylinux(PEP 600), biên dịch từ mã nguồn chậm10x–50xvà dễ đụng lỗi ngăn xếp luồng128 KB/ DNSndots:5. (3) Triển khai tag:latestvớiimagePullPolicy: IfNotPresentkhiến nút cũ chạy mã v1 trong khi nút mới kéo v2, gây lỗi lệch schema API. - Khắc phục: Thay
docker.sockbằng RootlessPodman/Buildah/BuildKitcô lập; chuẩn hóa ảnh nềnChainguard Wolfi (glibc)hoặcpython:3.12-slim-bookworm; và bắt buộc ghim@sha256:bất biến.
Case 6 — Khủng hoảng DB Chung Trên CI vs. Testcontainers (Netflix 14M Tests/Tháng) & Mạng internal: true#
- Thực tế Doanh nghiệp: Khi chạy kiểm thử song song trên CI bằng máy chủ PostgreSQL/Redis dùng chung hoặc cố định cổng
5432:5432, các job ghi đè dữ liệu chéo nhau và đụng lỗibind: address already in use. Netflix chuẩn hóa toàn bộ kiểm thử tích hợp trênTestcontainersvới quy mô~14 triệu ca kiểm thử/thángqua~850,000lượt build, cấp cổng host động cô lập hoàn toàn từng luồng kiểm thử và tự động dọn rác quaRyuksidecar. Song song, tầng mạngbackendcủa Compose phải luôn bậtinternal: trueđể khóa đường thoát Internet từ lớp dữ liệu.
Mã Nguồn Chuẩn Thực thi (cgroups v2 + OverlayFS 2W + Kiểm toán Dockerfile + Đồ thị Compose Bằng Python 3.12+)#
Đoạn mã hoàn chỉnh, tự trị dưới đây chạy trực tiếp 100% offline trên .venv Python 3.12+ (không cần Docker daemon đang chạy) để kiểm chứng đồng thời toán học cgroups v2, phình OverlayFS 2W, kiểm toán Dockerfile đối chứng, và sắp xếp topo Kahn cho docker-compose.yml:
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import Any
import numpy as np
import yaml
@dataclass(frozen=True, slots=True)
class CGroupSample:
cpu_quota_us: int
cpu_period_us: int
omp_threads: int
rss_mb: float
memory_max_mb: float
pid1_exec_form: bool
def evaluate_cgroups_v2_and_pid1(sample: CGroupSample, req_work_ms: float = 25.0) -> dict[str, Any]:
"""Derive CFS t_exhaust/t_stall, p99 burst latency, and SIGKILL (137) vs SIGTERM (143)."""
quota_ms = sample.cpu_quota_us / 1000.0
period_ms = sample.cpu_period_us / 1000.0
t_exhaust_ms = min(period_ms, quota_ms / max(1, sample.omp_threads))
t_stall_ms = max(0.0, period_ms - t_exhaust_ms)
# Multi-thread OpenMP burn consumes quota quickly and stalls until next 100ms refill
burn_rate = float(sample.omp_threads)
cpu_need = req_work_ms * (1.0 + 0.12 * max(0, sample.omp_threads - 1))
latencies: list[float] = []
for idx in range(30):
rem = cpu_need * (0.9 + 0.2 * (idx % 5) / 4.0)
budget = quota_ms if idx % 3 != 2 else quota_ms * 0.45
wall = 0.0
while rem > 1e-9:
if rem <= budget:
wall += rem / burn_rate
rem = 0.0
else:
exec_t = budget / burn_rate
wall += exec_t + max(0.0, period_ms - exec_t)
rem -= budget
budget = quota_ms
latencies.append(wall)
p99_ms = float(np.percentile(np.asarray(latencies, dtype=np.float64), 99))
oom_killed = sample.rss_mb >= sample.memory_max_mb
exit_code = 137 if (oom_killed or not sample.pid1_exec_form) else 143
return {
"t_exhaust_ms": round(t_exhaust_ms, 2),
"t_stall_ms": round(t_stall_ms, 2),
"p99_ms": round(p99_ms, 2),
"oom_killed": oom_killed,
"exit_code": exit_code,
}
def simulate_overlayfs_copyup_2w(base_mb: float, weights_mb: float, separate_chown: bool) -> dict[str, float]:
"""Quantify OverlayFS CoW 2W size amplification caused by separate RUN chmod/chown."""
l0 = base_mb
l1 = weights_mb
l2_copyup = weights_mb if separate_chown else 0.0
total = l0 + l1 + l2_copyup
return {
"total_oci_mb": round(total, 1),
"wasted_copyup_mb": round(l2_copyup, 1),
"weights_amplification": round((l1 + l2_copyup) / weights_mb, 2),
}
def verify_compose_dag_and_internal_net(compose_yaml: str) -> dict[str, Any]:
"""Parse Compose YAML, run Kahn topological boot sort, and audit internal:true isolation."""
doc = yaml.safe_load(compose_yaml)
services: dict[str, Any] = doc["services"]
networks: dict[str, Any] = doc.get("networks", {})
internal_nets = {k for k, v in networks.items() if isinstance(v, dict) and v.get("internal") is True}
in_deg = {name: len(cfg.get("depends_on", {})) for name, cfg in services.items()}
dependents: dict[str, list[str]] = {name: [] for name in services}
for name, cfg in services.items():
for dep in cfg.get("depends_on", {}):
dependents[dep].append(name)
q: deque[str] = deque(sorted(k for k, d in in_deg.items() if d == 0))
boot_order: list[str] = []
while q:
cur = q.popleft()
boot_order.append(cur)
for nxt in sorted(dependents[cur]):
in_deg[nxt] -= 1
if in_deg[nxt] == 0:
q.append(nxt)
db_isolated = all(
set(services[s].get("networks", [])) <= internal_nets and not services[s].get("ports")
for s in ("postgres", "redis")
)
return {"boot_order": boot_order, "internal_networks": sorted(internal_nets), "db_isolated": db_isolated}
if __name__ == "__main__":
pinned = evaluate_cgroups_v2_and_pid1(CGroupSample(100_000, 100_000, 2, 340.0, 512.0, True))
burst = evaluate_cgroups_v2_and_pid1(CGroupSample(100_000, 100_000, 16, 470.0, 512.0, False))
ov_bad = simulate_overlayfs_copyup_2w(120.0, 800.0, separate_chown=True)
ov_ok = simulate_overlayfs_copyup_2w(120.0, 800.0, separate_chown=False)
sample_compose = """
services:
postgres: { networks: [backend] }
redis: { networks: [backend] }
api:
ports: ["127.0.0.1:8000:8000"]
networks: [frontend, backend]
depends_on:
postgres: { condition: service_healthy }
redis: { condition: service_healthy }
networks:
frontend: { driver: bridge }
backend: { driver: bridge, internal: true }
"""
dag = verify_compose_dag_and_internal_net(sample_compose)
assert pinned["exit_code"] == 143 and burst["exit_code"] == 137
assert burst["p99_ms"] > pinned["p99_ms"] * 3.0
assert ov_bad["weights_amplification"] == 2.0 and ov_ok["wasted_copyup_mb"] == 0.0
assert dag["boot_order"] == ["postgres", "redis", "api"] and dag["db_isolated"] is True
print("Container Specimen OK:", {"pinned": pinned, "burst": burst, "ov_bad": ov_bad, "dag": dag})
Ba Bảng Ra quyết định Sản xuất 2026 (Production Decision Playbooks)#
Playbook A — Chọn Runtime Cô lập & Ảnh Nền Python/AI#
| Kịch bản Sản xuất | Lựa chọn Kiến trúc Chuẩn 2026 | Lựa chọn Phải Tránh | Lý do Định lượng & Bảo mật |
|---|---|---|---|
| Dịch vụ FastAPI / ML Nội bộ Chuẩn | Rootless Podman (crun + pasta) hoặc Docker (--cap-drop=ALL, USER >= 10001, --read-only) + Chainguard Wolfi (glibc) hoặc slim-bookworm |
python:3.12-alpine (musl), chạy root, gắn docker.sock |
Wolfi/Slim giữ tương thích PEP 600 manylinux (PyTorch, NumPy); Wolfi giảm CVE về 0, không shell cho kẻ tấn công. |
| Sandbox Chạy Mã Python/Agent LLM Không Tin cậy | Firecracker microVM (KVM /dev/kvm + jailer + VirtIO) |
Container Docker/Podman chuẩn dùng chung nhân | Chỉ Firecracker cô lập phần cứng ngăn khai thác ~300+ syscalls nhân trong <= 125 ms và < 5 MiB overhead. |
Gói Trọng số Lớn (> 1 GB PyTorch/LLM) |
COPY --chown=10001:10001 hoặc đa tầng + Model-Load từ Object Storage/Volume |
COPY rồi chạy riêng RUN chmod/chown |
Tránh nhân đôi dung lượng 2W qua OverlayFS copy-up (920 vs 1,720 MB trong Lab 05). |
Playbook B — Chọn Chiến lược Build BuildKit, uv & Chuỗi Cung ứng OCI#
| Hạng mục | Thực hành SOTA 2026 | Anti-Pattern Tuyệt đối Cấm | Thước đo Nghiệm thu |
|---|---|---|---|
| Thứ tự Lớp & Cache | --mount=type=bind cho pyproject.toml + uv.lock + --mount=type=cache,target=/root/.cache/uv với --no-install-project TRƯỚC COPY src/ |
COPY . . trước pip install |
Tốc độ build trung bình giảm 18.76x (68.3 s -> 3.64 s qua 10 commit), tiết kiệm 3,780 MB mạng. |
| Xử lý Bí mật Build | --mount=type=secret,id=... (chỉ nằm trong tmpfs suốt một bước RUN) + .dockerignore |
ARG TOKEN=..., ENV SECRET=..., COPY .env rồi RUN rm |
0 bí mật xuất hiện trong docker history --no-trunc và báo cáo trivy --scanners secret. |
| Registry & Triển khai | Harbor / GAR khử trùng lặp sha256 + SBOM + Trivy + Cosign v3.0 + ghim @sha256: |
Triển khai :latest / tag động không chữ ký |
Tiết kiệm 82.76% lưu trữ qua 6 tag; triệt tiêu trôi phiên bản split-brain ở IfNotPresent. |
Playbook C — Thiết kế Lưu trữ, Mạng Compose, cgroups v2 & Kiểm thử CI#
| Hạng mục Vận hành | Cấu hình & Ngưỡng An toàn | Bẫy Sập Phổ biến | Công cụ / Kiểm định Trong Lab 05 |
|---|---|---|---|
Lưu trữ & /dev/shm |
Named Volume (pgdata) cho DB; tmpfs cho /tmp (read_only: true); shm_size >= 2g–8g cho PyTorch |
Ghi DB vào lớp writable container; quên /dev/shm mặc định 64 MiB |
docker-compose.yml kiểm bởi analyze_compose_stack (Test 10). |
| Mạng & Khởi động DAG | Mạng kép frontend + backend (internal: true) (0 cổng DB ra host); depends_on: condition: service_healthy |
depends_on mặc định (service_started) + gắn DB ra cổng 5432:5432 |
boot_order = ['postgres', 'redis', 'api'], data_services_egress_isolated = True (Tests 08, 09). |
| Tín hiệu & Kiểm thử CI | Exec-form CMD + STOPSIGNAL SIGTERM + init: true; Testcontainers cổng động + Ryuk reaper |
Shell-form /bin/sh (Exit 137); DB staging tĩnh dùng chung |
Exit 143 khi tắt êm, testcontainers_reference/test_containers_e2e.py (Tests 02, 11). |
Trụ cột 4 — Phòng thí nghiệm Công nghiệp: container_ops_lab & Kiểm định 16/16 pytest#
4.1 Kiến trúc Gói & Hợp đồng Môi trường Offline Windows#
labs/lab-05-docker-compose-and-testcontainers/
├── pyproject.toml # fastapi, pydantic>=2, pyyaml, httpx, uvicorn, numpy; requires-python>=3.12, testpaths=["tests"]
├── uv.lock # Tệp khóa tái lập 32 gói (Python >=3.12) giải quyết qua uv lock
├── README.md # Hướng dẫn thực hành 100% tiếng Việt
├── Dockerfile # Đa tầng BuildKit (ARG TARGETARCH + sharing=locked) + uv + @sha256: đa kiến trúc + USER 10001 + exec CMD
├── Dockerfile.naive # Bản đối chứng chứa đầy đủ anti-pattern (lộ ARG/ENV, 2x copy-up, root, shell CMD)
├── .dockerignore # Chặn .git, .venv, .env*, tests/, testcontainers_reference/, artifacts/
├── docker-compose.yml # Stack api+postgres+redis: frontend + internal:true backend, pgdata, service_healthy, cap_drop: ALL
├── testcontainers_reference/
│ └── test_containers_e2e.py # Bộ kiểm thử Testcontainers E2E thực tế (cổng động + WaitStrategy + Ryuk)
├── src/
│ └── container_ops_lab/
│ ├── __init__.py
│ ├── linux_isolation_sim.py # Tier 1: 7 Namespaces, cgroups v2 CFS/OOM, OverlayFS 2W/whiteout, BuildKit cache, OCI sha256 dedup
│ ├── container_audit_and_compose.py # Trình phân tích AST/Regex Dockerfile + PyYAML Compose Kahn DAG & kiểm tra internal:true
│ └── app.py # Ứng dụng FastAPI thật (/health/live, /health/ready, /v1/container-score, /v1/stack-status)
├── scripts/
│ └── run_lab_demo.py # CLI kiểm toán tệp hạ tầng thật, chạy mô phỏng & xuất artifacts/t2_ch06_lab05_results.json
├── tests/
│ └── test_container_ops_lab.py # 16 ca pytest (0 skip offline) + quét AST chỉ cấm giải tuần tự nguy hiểm
└── artifacts/
└── t2_ch06_lab05_results.json # Báo cáo thực nghiệm định lượng (6 KPI, 4 bars, 4 tables)
Hợp đồng Thực thi Offline trên Windows (dockerd Không Bật): Trong môi trường Windows host chỉ có client docker.exe 27.3.1 mà không bật máy ảo Docker Desktop Linux engine, pyproject.toml cấu hình testpaths = ["tests"] để giữ riêng bộ Testcontainers thật trong testcontainers_reference/test_containers_e2e.py (sẵn sàng chạy bằng pytest testcontainers_reference/test_containers_e2e.py -v trên Linux/WSL2/CI có daemon). Đồng thời, bộ tests/test_container_ops_lab.py đạt 16/16 PASS (0 skipped) hoàn toàn offline bằng cách: (1) phân tích cú pháp thực tế Dockerfile, Dockerfile.naive, .dockerignore và docker-compose.yml qua PyYAML; (2) chạy toàn bộ bộ mô phỏng Tầng nhân Linux / cgroups v2 / OverlayFS / BuildKit / OCI Registry; và (3) kiểm thử dịch vụ FastAPI trong tiến trình qua httpx.ASGITransport. Bộ quét AST ở test_16 chỉ cấm các mô-đun giải tuần tự không an toàn (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal).
4.2 Thực thi CLI & Bảng 6 Chỉ số Thực nghiệm (artifacts/t2_ch06_lab05_results.json)#
D:\FSDS-SOTA-Curriculum\.venv\Scripts\python.exe scripts/run_lab_demo.py --output artifacts/t2_ch06_lab05_results.json
Chỉ số KPI (artifacts/t2_ch06_lab05_results.json) |
Giá trị Đo kiểm Thực tế (.venv Python 3.12.16) |
Trạng thái |
|---|---|---|
kpi_dockerfile_hardening_score (Dockerfile vs. Dockerfile.naive) |
100 vs 0/100 (175.0 vs 1255.0 MB; bản chuẩn 2 tầng uv, @sha256:, USER 10001, exec CMD, HEALTHCHECK; bản ngây thơ lộ 2 bí mật ARG/ENV & dính 11 lỗi) |
ok (Đã xác minh) |
kpi_cgroups_v2_cfs_and_exit_codes (CFS Burst & Exit 137 vs 143) |
16.1 vs 176.08 ms p99 (10.94x p99 spike; 16 luồng đốt 100 ms trong 6.25 ms rồi treo 93.75 ms, throttle_ratio=24.53%; OOM/shell CMD \(\to\) Exit 137 vs exec/tini \(\to\) Exit 143) |
warn (Đã xác minh) |
kpi_overlayfs_2w_copyup (Inline --chown vs. RUN chmod riêng) |
920 vs 1720 MB (2.0x weights; tách RUN chmod/chown nhân đôi 800 MB trọng số qua upperdir copy-up; thêm RUN rm chỉ tạo .wh.model.safetensors giữ nguyên 1,720.01 MB) |
ok (Đã xác minh) |
kpi_buildkit_uv_layer_cache (10 commits sửa src/) |
68.3s -> 3.64s (18.76x faster; cache hit 30.0% -> 60.0%, tổng thời gian CI giảm 683.0s -> 36.4s, tiết kiệm 3,780 MB tải lại thư viện) |
ok (Đã xác minh) |
kpi_oci_registry_dedup (Harbor sha256 Dedup qua 6 Tags) |
7461 -> 1286 MB (-82.76% storage; HEAD /v2/.../blobs/<digest> bỏ qua 10/18 lớp trùng khi đẩy 6 phiên bản) |
ok (Đã xác minh) |
kpi_compose_internal_and_asgi (Compose DAG + internal:true + ASGI) |
postgres -> redis -> api (0 DB host ports; service_healthy=True, data_services_egress_isolated=True, ASGI live=200/ready=200) |
ok (Đã xác minh) |
4.3 Hợp đồng 16 Ca Kiểm thử pytest (tests/test_container_ops_lab.py)#
Toàn bộ 16/16 ca kiểm thử đạt xanh tuyệt đối (16 passed, 0 warnings, 0 skips), ruff check src scripts tests testcontainers_reference đạt All checks passed!, mypy src (strict = true) đạt 0 lỗi, và uv.lock khóa sạch 32 gói (Python >=3.12):
| # | Tên Hàm Kiểm thử (test_container_ops_lab.py) |
Khẳng định & Bất biến Bắt buộc |
|---|---|---|
| 1 | test_01_namespace_isolation_rootful_vs_rootless_podman_vs_firecracker |
Đối chiếu 7 Namespaces (PID, NET, MNT, UTS, IPC, USER, CGROUP), rủi ro docker.sock (UID 0) ở Docker, ánh xạ UID >= 100000 không daemon của Podman (crun, 34 ms), và tính an toàn KVM của Firecracker (<= 125 ms). |
| 2 | test_02_cgroups_v2_cfs_throttling_and_oom_exit_137_vs_143 |
Kiểm chứng 16 luồng đốt nhanh hơn và treo t_stall đẩy p99 vọt > 1.5x (10.94x), kích hoạt reclaim_throttled khi vượt memory.high, phân tách Exit 143 (exec_tini) với Exit 137 (shell_form & oom_killed). |
| 3 | test_03_overlayfs_cow_2w_bloat_and_whiteouts |
Xác nhận inline COPY --chown giữ ảnh ở 920 MB (1.0x), tách RUN chmod/chown phình lên 1,720 MB (2.0x), và RUN rm tạo /models/.wh.model.safetensors che tệp ở merged (120 MB) nhưng không thu nhỏ gói ảnh (> 1,720 MB). |
| 4 | test_04_buildkit_uv_split_layer_cache_efficiency |
Xác minh chiến lược bind-mount pyproject.toml/uv.lock + --mount=type=cache tăng hit rate 30% -> 60%, tăng tốc CI >= 4.0x (18.76x), và tiết kiệm >= 3,000 MB (3,780 MB). |
| 5 | test_05_oci_registry_sha256_blob_deduplication |
Kiểm định thuật toán khử trùng lặp blob sha256 qua 6 bản phát hành giảm >= 75% dung lượng (82.76%), chỉ tải 8 blob duy nhất thay vì 18 lượt (10 lượt bỏ qua qua HEAD). |
| 6 | test_06_real_hardened_dockerfile_and_dockerignore_audit |
Phân tích trực tiếp Dockerfile và .dockerignore thật của lab: 2 stages, @sha256:, 0 bí mật lộ, non_root=True, exec-form CMD, HEALTHCHECK, STOPSIGNAL, đạt 100/100 (HARDENED). |
| 7 | test_07_real_naive_dockerfile_detects_all_anti_patterns |
Phân tích trực tiếp Dockerfile.naive: bắt trọn vẹn DF001–DF012 (đơn tầng, :latest, lộ ARG/ENV, COPY . trước pip, tách RUN chmod/chown, root, shell-form CMD, thiếu HEALTHCHECK), xếp INSECURE (0/100). |
| 8 | test_08_real_docker_compose_topological_boot_dag |
Dùng PyYAML phân tích docker-compose.yml thật: thuật toán Kahn xuất thứ tự postgres và redis trước api, 100% cạnh dùng service_healthy, có volume pgdata. |
| 9 | test_09_real_docker_compose_dual_network_internal_egress_isolation |
Xác minh mạng frontend (internal=False), mạng backend (internal=True), postgres/redis chỉ nằm trên backend với 0 cổng mở ra host, còn api nối cả hai. |
| 10 | test_10_real_docker_compose_least_privilege_hardening |
Kiểm tra từng dịch vụ trong docker-compose.yml thật: api và redis bật read_only, tmpfs, cap_drop: [ALL], no-new-privileges:true, init: true, và giới hạn tài nguyên deploy.resources.limits. |
| 11 | test_11_testcontainers_reference_syntax_and_contracts |
Kiểm tra AST và hợp đồng API của testcontainers_reference/test_containers_e2e.py (PostgresContainer, RedisContainer, LogMessageWaitStrategy, HttpWaitStrategy, get_exposed_port, cap_drop, read_only=True). |
| 12 | test_12_fastapi_container_app_probes_and_degraded_drain |
Chạy httpx.ASGITransport + lifespan_context không cần daemon: xác nhận /health/live == 200 cả khi degraded=True, còn /health/ready trả 503 application/problem+json khi degraded hoặc draining. |
| 13 | test_13_fastapi_container_score_strict_pydantic_v2_and_stack_status |
Gửi payload hợp lệ và payload sai ("1.0", trường lạ extra_rogue) tới /v1/container-score (422 problem+json) và đọc kiểm toán stack thật qua /v1/stack-status bằng httpx.ASGITransport. |
| 14 | test_14_cli_run_lab_demo_quick_exports_expected_schema |
Chạy tiến trình con scripts/run_lab_demo.py --quick --output ... kiểm chứng docker_daemon_required == False, đủ 6 KPI, 4 biểu đồ thanh, 4 bảng. |
| 15 | test_15_artifact_results_json_in_sync_and_valid |
Đọc artifacts/t2_ch06_lab05_results.json đối chiếu tính nhất quán: hardened 100/100, naive <= 20/100, data_services_egress_isolated == True. |
| 16 | test_16_security_only_ast_scan_no_unsafe_deserialization |
Quét AST toàn bộ tệp .py trong src/, scripts/, tests/, testcontainers_reference/ bảo đảm 0 import giải tuần tự nguy hiểm (pickle, joblib, cloudpickle, dill, shelve, marshal). |
Trụ cột 5 — Tài liệu Đọc SOTA 2024–2026 & Bài tập Đánh giá Năng lực#
5.1 Danh mục Tài liệu Kinh điển & Chuẩn Kỹ thuật (Curated Reading List)#
- Open Container Initiative (
OCI, 2024–2026). OCI Image Format Specification v1.1, Runtime Specification v1.1 & Distribution Specification v1.1 (incl. Referrers API).
Vì sao quan trọng: Chuẩn hóa hoàn toàn định dạng lớpDiffID/ChainID, tệp cấu hìnhconfig.jsoncủarunc/crun, giao thức khử trùng lặp/v2/blobs/và gắn chữ ký/SBOM theosubject. - Linux Kernel Documentation (Torvalds et al., 2024–2026). Control Group v2 (
Documentation/admin-guide/cgroup-v2.rst) & Overlay Filesystem (Documentation/filesystems/overlayfs.rst).
Vì sao quan trọng: Tài liệu gốc định nghĩa ngữ nghĩacpu.max/cpu.stat, ranh giớimemory.highvs.memory.max(OOM), cơ chếcopy-upvà whiteout.wh.*trênupperdir/lowerdir. - Agache, A. et al. (AWS / USENIX NSDI 2020) & Chiluk, D. (Indeed / Kubernetes
#67577). Firecracker: Lightweight Virtualization for Serverless Applications & Unthrottled: Fixing CPU Limits in the Cloud.
Vì sao quan trọng: Lý giải mô hình cô lập phần cứng< 5 MiB/<= 125 mscho sandbox AI đa người thuê và căn nguyên thảm họap99từ điều tiết CFS bandwidth100 ms. - Astral
uvDocker Integration Guide + Python PEPs600&656(2024–2026). Usinguvin Docker (--mount=type=cache/bind,--locked,--no-install-project) &manylinuxvs.musllinuxWheel ABI Standards.
Vì sao quan trọng: Đặt chuẩn công nghiệp mới cho tách lớp bộ nhớ đệm Python không cầnpip, đồng thời chứng minh vì saoAlpine(musl) phá vỡ hệ sinh thái wheel AI (PyTorch/NumPy) so vớiWolfi/Debian-slim(glibc). - Tsouvalas, B. & Nikiforakis, N. (Stony Brook University, ACM CCS). Uncovering Credential Leaks in Public Container Registries (300-Image Honeypot Empirical Study).
Vì sao quan trọng: Chứng minh bằng thực nghiệm việc rò rỉ bí mật trongARG/ENV/docker historybị khai thác chỉ sau7.86 giây, buộc chuyển sang BuildKit--mount=type=secretvà.dockerignore. - OpenSSF
SLSA v1.1(04/2025), SigstoreCosign v3.0(10/2025), Docker Compose Spec &Testcontainers-Python 4.xDocs.
Vì sao quan trọng: Chuẩn hóa ký không khóa OIDC (.sigstore.json+ Fulcio + Rekor), SBOM (SPDX 3.0/CycloneDX 1.6), điều phốiservice_healthy+internal: true, và kiểm thử tích hợp không đụng độ cổng vớiRyuk.
5.2 Tám Điểm Kiểm tra Tư duy (Q1–Q8) & Sáu Bài tập Trọng số#
- Q1 (VMs vs. Containers vs. Firecracker &
7Namespaces): Phân biệtchrootvớipivot_root + umount2(MNT_DETACH), vai trò của/etc/subuidtrongCLONE_NEWUSER, và lý do sandbox chạy mã LLM không tin cậy bắt buộc cầnFirecracker microVM. - Q2 (
cgroups v2cpu.max,memory.highvs.memory.max&Exit 137): Tính \(t_{\text{exhaust}}\) và \(t_{\text{stall}}\) khiOMP_NUM_THREADS=16chạy dưới1.0 vCPU(6.25 msvs93.75 ms), giải thích khác biệt giữa direct reclaim và OOM killer. - Q3 (
OverlayFS2WCopy-on-Write & Whiteouts): Chứng minh vì saoRUN chmod/chownở lớp riêng biến800 MBtrọng số thành1,600 MB(1,720 MBtổng) và vì saoRUN rmchỉ ghi.wh.*mà không thu nhỏ gói ảnh. - Q4 (
Dockervs. RootlessPodman& BẫyPID 1): So sánh chuỗidockerd -> containerd -> shim -> runcvớipodman -> fork-exec -> conmon -> crun + pasta, giải thích rủi rodocker.sockvà lý do shell-formCMDgâyExit 137thay vì143. - Q5 (
BuildKitDAG,uvSplit & Rò rỉARG/ENV): Trình bày cơ chế bind-mountpyproject.toml/uv.lock+--mount=type=cacheđạt18.76xtốc độ rebuild, và cơ chế--mount=type=secretkhắc phục lỗ hổng7.86 giâytừdocker history. - Q6 (
Wolfivs.Alpinemusl,SBOM,Cosign&Harbor): Giải thích xung độtPEP 600(glibc) vsPEP 656(musl), quy trìnhSyft/Trivy -> Cosign v3.0 -> Harbor, và cơ chế khử trùng lặpsha256tiết kiệm82.76%dung lượng kèm@sha256:pinning. - Q7 (
Docker ComposeTopo DAG & Mạnginternal: true): Mô tả thuật toán Kahn trêndepends_on: service_healthy, phân giải DNS127.0.0.11, và tác dụng chặn rò rỉ dữ liệu ra Internet khi gắnpostgres/redisvàointernal: true. - Q8 (Ephemeral
Testcontainersvs. Shared Staging DB): Giải thích vì sao cổng host động ngẫu nhiên +LogMessageWaitStrategy+Ryuksidecar loại bỏ xung đột cổng5432và rác CI trong kiểm thửpytest-xdist.
Sáu Bài tập Thực hành (Gợi ý Từng bước Tích hợp Tại Mục Quiz Cuối Trang)#
- Bài tập 1 (15 điểm) — Cô lập Tầng nhân:
7Namespaces,pivot_root& Đối chứng Runtime:- Bước thực hành: Gọi
evaluate_namespace_isolationchorootful_docker,rootless_podman, vàfirecracker_microvm; phân tích inode/proc/<pid>/ns/*, ánh xạUID 0 -> 100000, và lý do bỏ quachroot. - Tiêu chí đạt: Xác minh
rootless_podmancô lập7/7namespaces không cần daemon (34 ms),firecracker_microvmđạtuntrusted_ai_sandbox_safe=True, vượttest_01.
- Bước thực hành: Gọi
- Bài tập 2 (20 điểm) —
cgroups v2CFS Burst Trap, Ngưỡng RAM & Tín hiệuPID 1:- Bước thực hành: Gọi
simulate_cgroups_v2_throttling_and_oomso sánhpinned(active_threads=2,340 MiB,exec_tini) vớiburst(active_threads=16,470 MiB,shell_form) vàoom(512 MiB). - Tiêu chí đạt: Chứng minh
p99nhảy16.1 -> 176.08 ms(10.94x),reclaim_throttled=Truetại470 MiB, phân biệt rạch ròiExit 143vsExit 137, vượttest_02.
- Bước thực hành: Gọi
- Bài tập 3 (15 điểm) —
OverlayFS2W,BuildKituvSplit &Harborsha256Deduplication:- Bước thực hành: Chạy
simulate_overlayfs_cow_and_whiteouts,simulate_buildkit_layer_cache, vàsimulate_oci_registry_deduplicationtrêncontainer_ops_lab. - Tiêu chí đạt: Định lượng
920 vs 1,720 MB(2.0x) +.wh.model.safetensors, tốc độ rebuild18.76x(68.3 -> 3.64 s), và tiết kiệm82.76%dung lượng trên Registry, vượttest_03–test_05.
- Bước thực hành: Chạy
- Bài tập 4 (15 điểm) — Kiểm toán Thực tế
DockerfileĐa tầng vs.Dockerfile.naive:- Bước thực hành: Đọc và chạy
audit_dockerfiletrên hai tệp thậtDockerfile+.dockerignorevàDockerfile.naivetrong thư mục Lab 05. - Tiêu chí đạt:
Dockerfileđạt100/100 (HARDENED)(175.0 MB), cònDockerfile.naivebị chấm0/100 (INSECURE)(1,255.0 MB) với đủ các lỗiDF001..DF012, vượttest_06–test_07.
- Bước thực hành: Đọc và chạy
- Bài tập 5 (15 điểm) — Phân tích Đồ thị
Compose(service_healthy), Mạnginternal: true&Testcontainers:- Bước thực hành: Gọi
analyze_compose_stack(Path("docker-compose.yml"))kiểm tra thứ tự topo, mạngbackend (internal: true)và các cờcap_drop/read_only/tmpfs; kiểm tra hợp đồngtestcontainers_reference/test_containers_e2e.py. - Tiêu chí đạt: Thu được
boot_order = ['postgres', 'redis', 'api'],data_services_egress_isolated=True,0host ports ở DB/Redis, vượttest_08–test_11.
- Bước thực hành: Gọi
- Bài tập 6 (20 điểm) — Kiểm định Dịch vụ
FastAPIQuahttpx.ASGITransport, CLI JSON & Cổng16/16 pytest:- Bước thực hành: Kiểm tra
/health/live,/health/ready,/v1/container-score,/v1/stack-statusquahttpx.ASGITransport; chạyruff,mypy --strict,run_lab_demo.py, vàpytest -p no:cacheprovider -v. - Tiêu chí đạt:
ruff0lỗi,mypy0lỗi,artifacts/t2_ch06_lab05_results.jsonđủ6KPI /4bars /4tables, AST0import cấm (pickle/joblib/...), và16/16 pytestPASS.
- Bước thực hành: Kiểm tra
5.3 Thang Điểm & Tiêu chuẩn Nghiệm thu (Grading Rubric — 100 Điểm)#
| Hạng mục Đánh giá | Trọng số | Tiêu chí Đạt Chuẩn Nghiệm thu (>= 80/100) |
Lệnh / Ca Kiểm thử Đối chứng |
|---|---|---|---|
1. Tầng nhân Namespaces, cgroups v2 & OverlayFS 2W |
25 | Phân biệt đúng Docker / Podman / Firecracker, tái hiện 10.94x CFS stall & Exit 137 vs 143, chứng minh 2W copy-up & .wh.*. |
Tests 01, 02, 03 |
2. BuildKit uv Cache & OCI sha256 Deduplication |
15 | Tăng hit rate tách lockfile (18.76x CI speedup) và khử trùng lặp blob sha256 (>= 75% tiết kiệm). |
Tests 04, 05 |
3. Kiểm toán Thực tế Dockerfile & .dockerignore |
20 | Dockerfile đạt 100/100 (HARDENED) (@sha256:, USER 10001, exec CMD), Dockerfile.naive bắt đủ 11 lỗi (INSECURE). |
Tests 06, 07 |
4. Docker Compose Topo DAG, internal: true & Testcontainers |
20 | Khởi động postgres -> redis -> api (service_healthy), 0 cổng DB ra host, cap_drop: ALL, read_only, hợp đồng Testcontainers + Ryuk. |
Tests 08, 09, 10, 11 |
5. Dịch vụ FastAPI ASGI, CLI JSON & Quality Gates (ruff/mypy/AST) |
20 | /health/* & /v1/container-score (422 problem+json), CLI xuất đủ 6 KPI/4 bars/4 tables, ruff+mypy 0 lỗi, 16/16 pytest PASS. |
Tests 12, 13, 14, 15, 16 + ruff + mypy |
| Tổng cộng | 100 | Đạt tối thiểu 80/100 tổng điểm và không có mục nào 0 điểm (toàn bộ 16/16 test phải PASS). |
pytest -p no:cacheprovider -v |
cgroups v2 cpu.max=100ms: Pinned OMP=2 vs Unpinned 16-Thread Burst p99 (ms)
OverlayFS 800 MB Weights: Inline --chown vs Separate RUN chmod + Late rm (MB)
CI Build Time Across 10 Commits: COPY-Early pip vs BuildKit uv Split (s)
Harbor Content-Addressable Registry Storage & Hardened Dockerfile Audit
Container Runtime Comparison: Docker Rootful vs Rootless Podman vs Firecracker
| runtime_mode | oci_or_vmm_engine | isolated_namespaces | host_uid_for_container_root | cold_start_ms | untrusted_ai_sandbox_safe |
|---|---|---|---|---|---|
| rootful_docker | runc | 6/7 (USER=False) | 0 | 48.0 ms (6.5 MiB) | False |
| rootless_podman | crun | 7/7 (USER=True) | 100000 | 34.0 ms (2.8 MiB) | False |
| firecracker_microvm | firecracker-vmm | 7/7 (USER=True) | 10001 | 118.0 ms (4.5 MiB) | True |
cgroups v2 CPU Quota, Memory Limits & PID 1 Signal Exit Matrix
| scenario | threads_vs_quota | t_exhaust_vs_stall_ms | p99_latency_ms | exit_code | diagnosis |
|---|---|---|---|---|---|
| pinned_exec_tini | 2 thr / 1.0 vCPU | 50.0 / 50.0 ms | 16.1 ms | 143 (SIGTERM) | Healthy low-jitter & graceful exit |
| unpinned_cfs_burst_shell_pid1 | 16 thr / 1.0 vCPU | 6.25 / 93.75 ms | 176.08 ms | 137 (SIGKILL) | CFS stall + /bin/sh swallowed SIGTERM |
| oom_memory_max_breach | 520.0 / 512.0 MiB | 25.0 / 75.0 ms | 9.77 ms | 137 (OOMKilled) | memory.max exceeded -> Kernel SIGKILL |
Real Lab Dockerfile Audit: Hardened Multi-Stage uv vs Dockerfile.naive
| dockerfile | stages_and_pin | non_root_and_pid1 | secret_leaks | projected_mb | score_and_grade |
|---|---|---|---|---|---|
| Dockerfile | 2 stages, sha256=True | non_root=True, exec=True | 0 | 175.0 MB | 100/100 (HARDENED) |
| Dockerfile.naive | 1 stage, latest=True | non_root=False, exec=False | 2 | 1255.0 MB | 0/100 (INSECURE) |
Real docker-compose.yml Service Topology, Network Segmentation & Hardening Audit
| service | networks | host_ports | egress_isolated | read_only_and_cap_drop | healthcheck |
|---|---|---|---|---|---|
| postgres | backend | none | True | ro=False, cap_ALL=False | True |
| redis | backend | none | True | ro=True, cap_ALL=True | True |
| api | frontend, backend | 127.0.0.1:8000:8000 | False | ro=True, cap_ALL=True | True |
03-track-2-data-and-ai-engineering/part-01-software-systems-foundations/labs/lab-05-docker-compose-and-testcontainers
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "container-ops-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 Lab 05: Linux Isolation (Namespaces/cgroups v2/OverlayFS), Hardened Multi-Stage Dockerfiles, Dual-Network Compose & Ephemeral Testcontainers"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115",
"pydantic>=2.0",
"pyyaml>=6.0",
"uvicorn>=0.30",
"httpx>=0.27",
"numpy>=1.24",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.8",
"mypy>=1.10",
]
[project.scripts]
fsds-container-lab = "container_ops_lab.app:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.ruff]
target-version = "py312"
line-length = 105
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "RUF"]
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
[[tool.mypy.overrides]]
module = ["yaml"]
ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
# syntax=docker/dockerfile:1.11
# Hardened Multi-Stage BuildKit + uv Dockerfile for container_ops_lab
FROM python:3.12-slim-bookworm@sha256:935c3c5b12357a7e10caa9c1e6ca5692344d97cf229832ef584be2cec9fc03df AS builder
ARG TARGETARCH
COPY --from=ghcr.io/astral-sh/uv:0.6.14@sha256:3362a526af7eca2fcd8604e6a07e873fb6e4286d8837cb753503558ce1213664 /uv /uvx /bin/
ENV UV_COMPILE_BYTECODE=1 \
UV_LINK_MODE=copy \
UV_NO_DEV=1
WORKDIR /app
# Stage 1: Install third-party dependencies using bind mounts + persistent BuildKit cache
# Keeps dependency layer cached across source-only edits to src/.
RUN --mount=type=cache,id=uv-${TARGETARCH},sharing=locked,target=/root/.cache/uv \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
uv sync --locked --no-dev --no-install-project
# Stage 2: Copy application source with inline ownership (avoids OverlayFS 2W copy-up)
COPY --chown=10001:10001 src/ ./src/
COPY --chown=10001:10001 pyproject.toml uv.lock ./
RUN --mount=type=cache,id=uv-${TARGETARCH},sharing=locked,target=/root/.cache/uv \
uv sync --locked --no-dev --no-editable
FROM python:3.12-slim-bookworm@sha256:935c3c5b12357a7e10caa9c1e6ca5692344d97cf229832ef584be2cec9fc03df AS runtime
RUN groupadd --gid 10001 appgroup \
&& useradd --uid 10001 --gid 10001 --create-home --shell /usr/sbin/nologin appuser
WORKDIR /app
COPY --from=builder --chown=10001:10001 /app/.venv /app/.venv
COPY --from=builder --chown=10001:10001 /app/src /app/src
ENV PATH="/app/.venv/bin:$PATH" \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
OMP_NUM_THREADS=2 \
MKL_NUM_THREADS=2 \
MALLOC_MMAP_THRESHOLD_=65536 \
MALLOC_TRIM_THRESHOLD_=65536
USER 10001:10001
EXPOSE 8000
STOPSIGNAL SIGTERM
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --retries=3 \
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health/live', timeout=2)"]
# Exec form ensures uvicorn receives SIGTERM directly instead of /bin/sh swallowing signals
CMD ["uvicorn", "container_ops_lab.app:create_container_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--timeout-keep-alive", "75"]
# Anti-pattern Dockerfile kept intentionally for quantitative security & layer auditing
FROM python:latest
# Trap 1: Secrets in ARG/ENV remain permanently inspectable in docker history & OCI config JSON
ARG REGISTRY_BUILD_TOKEN=insecure_arg_token_demo
ENV MODEL_API_SECRET=insecure_env_secret_demo
WORKDIR /app
# Trap 2: Copying all context BEFORE installing dependencies busts layer cache on every code edit
COPY . /app
# Trap 3: Legacy pip install without BuildKit cache mount on heavy full base image
RUN pip install --no-cache-dir fastapi uvicorn pydantic pyyaml httpx numpy
# Trap 4: Separate chown/chmod RUN triggers OverlayFS copy-up doubling copied layer footprint (2W)
RUN chmod -R 0755 /app && chown -R nobody:nogroup /app
# Trap 5: Implicit root user (UID 0), no HEALTHCHECK, and shell-form CMD wrapping in /bin/sh -c
# which ignores SIGTERM -> 10s-30s stall -> SIGKILL Exit Code 137
CMD uvicorn container_ops_lab.app:create_container_app --factory --host 0.0.0.0 --port 8000
.git/
.gitignore
.venv/
.env
.env.*
**/*.pem
**/*.key
**/*.crt
__pycache__/
*.pyc
*.pyo
.pytest_cache/
.mypy_cache/
.ruff_cache/
tests/
testcontainers_reference/
artifacts/
*.md
Dockerfile*
docker-compose.yml
services:
postgres:
image: postgres:16-bookworm@sha256:ce3efec6bc404f6b15ebf5d9bed6b45a9d4655aea238d7dacc3467ccb05a1175
restart: unless-stopped
environment:
POSTGRES_USER: fsds
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-fsds_local_dev_only}
POSTGRES_DB: container_ops
networks:
- backend
volumes:
- pgdata:/var/lib/postgresql/data
shm_size: "256m"
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
healthcheck:
test: ["CMD-SHELL", "pg_isready -U fsds -d container_ops"]
interval: 5s
timeout: 3s
retries: 10
start_period: 10s
redis:
image: redis:7.4-bookworm@sha256:2e3eb11462c4e3759e6972678dd051d150ff54b1e60714b3c33b701260172a90
restart: unless-stopped
command: ["redis-server", "--save", "", "--appendonly", "no"]
networks:
- backend
read_only: true
tmpfs:
- /data:rw,noexec,nosuid,nodev,size=64m
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.5"
memory: 256M
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 10
api:
build:
context: .
dockerfile: Dockerfile
target: runtime
restart: unless-stopped
init: true
ports:
- "127.0.0.1:8000:8000"
networks:
- frontend
- backend
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
environment:
DATABASE_URL: postgresql://fsds:${POSTGRES_PASSWORD:-fsds_local_dev_only}@postgres:5432/container_ops
REDIS_URL: redis://redis:6379/0
OMP_NUM_THREADS: "2"
read_only: true
tmpfs:
- /tmp:rw,noexec,nosuid,nodev,size=64m
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
stop_grace_period: 30s
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
healthcheck:
test:
[
"CMD",
"python",
"-c",
"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health/live', timeout=2)",
]
interval: 10s
timeout: 3s
retries: 5
start_period: 10s
networks:
frontend:
driver: bridge
backend:
driver: bridge
internal: true
volumes:
pgdata: {}
"""Live Docker/Testcontainers E2E reference suite (requires running Docker/Podman daemon).
Kept outside pyproject.toml's testpaths=['tests'] so offline Windows/CI hosts without a
running container daemon still achieve 16/16 offline pytest verification.
Run on a host with Docker/Podman socket active via:
pytest testcontainers_reference/test_containers_e2e.py -v
"""
from __future__ import annotations
import os
from collections.abc import Iterator
from pathlib import Path
import httpx
import pytest
from testcontainers.core.container import DockerContainer
from testcontainers.core.image import DockerImage
from testcontainers.core.wait_strategies import HttpWaitStrategy, LogMessageWaitStrategy
from testcontainers.postgres import PostgresContainer
from testcontainers.redis import RedisContainer
LAB_ROOT = Path(__file__).resolve().parents[1]
@pytest.fixture(scope="module")
def ephemeral_pg_and_redis() -> Iterator[tuple[str, str]]:
"""Spin up ephemeral PostgreSQL 16 + Redis 7 on dynamic host ports cleaned up by Ryuk."""
pg = PostgresContainer("postgres:16-bookworm").waiting_for(
LogMessageWaitStrategy("database system is ready to accept connections")
)
redis = RedisContainer("redis:7.4-bookworm").waiting_for(
LogMessageWaitStrategy("Ready to accept connections")
)
with pg, redis:
pg_port = pg.get_exposed_port(5432)
redis_port = redis.get_exposed_port(6379)
pg_url = pg.get_connection_url()
redis_url = f"redis://{redis.get_container_host_ip()}:{redis_port}/0"
assert int(pg_port) != 5432 or os.getenv("TESTCONTAINERS_ALLOW_STATIC") == "1"
yield pg_url, redis_url
def test_e2e_ephemeral_postgres_redis_dynamic_ports(
ephemeral_pg_and_redis: tuple[str, str],
) -> None:
"""Verify Testcontainers assigns collision-free ephemeral host ports and clean startup."""
pg_url, redis_url = ephemeral_pg_and_redis
assert "postgresql" in pg_url
assert redis_url.startswith("redis://")
def test_e2e_built_api_container_health_and_score() -> None:
"""Build hardened Dockerfile image and test /health/live, /health/ready & /v1/container-score."""
with DockerImage(path=str(LAB_ROOT), tag="container-ops-lab:e2e") as image:
container = (
DockerContainer(str(image))
.with_exposed_ports(8000)
.with_kwargs(
read_only=True,
tmpfs={"/tmp": "rw,noexec,nosuid,nodev,size=64m"},
cap_drop=["ALL"],
security_opt=["no-new-privileges:true"],
)
.waiting_for(HttpWaitStrategy(port=8000).for_path("/health/ready").for_status_code(200))
)
with container:
host = container.get_container_host_ip()
port = container.get_exposed_port(8000)
base_url = f"http://{host}:{port}"
live = httpx.get(f"{base_url}/health/live", timeout=3.0)
assert live.status_code == 200
assert live.json()["status"] == "alive"
score = httpx.post(
f"{base_url}/v1/container-score",
json={
"workload_name": "e2e-probe",
"cpu_quota_vcpus": 1.0,
"omp_threads": 2,
"rss_mb": 320.0,
"memory_max_mb": 512.0,
"weights_mb": 400.0,
"separate_chown": False,
},
timeout=3.0,
)
assert score.status_code == 200
assert score.json()["exit_code_predicted"] == 0
"""FSDS-SOTA-2026 Track 2 Lab 05: Container Internals, Audit & Compose Lab."""
from container_ops_lab.app import create_container_app
from container_ops_lab.container_audit_and_compose import (
analyze_compose_stack,
audit_dockerfile,
)
from container_ops_lab.linux_isolation_sim import (
KERNEL_NAMESPACES,
evaluate_namespace_isolation,
simulate_buildkit_layer_cache,
simulate_cgroups_v2_throttling_and_oom,
simulate_oci_registry_deduplication,
simulate_overlayfs_cow_and_whiteouts,
)
__all__ = [
"KERNEL_NAMESPACES",
"analyze_compose_stack",
"audit_dockerfile",
"create_container_app",
"evaluate_namespace_isolation",
"simulate_buildkit_layer_cache",
"simulate_cgroups_v2_throttling_and_oom",
"simulate_oci_registry_deduplication",
"simulate_overlayfs_cow_and_whiteouts",
]
"""Tier 1 Linux container primitives, cgroups v2, OverlayFS CoW, BuildKit cache & OCI deduplication."""
from __future__ import annotations
import hashlib
import math
from dataclasses import dataclass
from typing import Any
import numpy as np
KERNEL_NAMESPACES: tuple[str, ...] = ("PID", "NET", "MNT", "UTS", "IPC", "USER", "CGROUP")
_RUNTIME_PROFILES: dict[str, dict[str, Any]] = {
"rootful_docker": {
"architecture_chain": (
"docker CLI -> /var/run/docker.sock -> dockerd (root) -> "
"containerd -> containerd-shim-runc-v2 -> runc"
),
"daemon_required": True,
"oci_runtime": "runc",
"network_driver": "veth + bridge (docker0/br-*)",
"storage_driver": "overlay2 (kernel OverlayFS)",
"root_uid_on_host": 0,
"subuid_mapping": None,
"user_ns_isolated": False,
"hardware_vm_isolation": False,
"shared_host_syscalls": 300,
"cold_start_ms": 48.0,
"control_overhead_mib": 6.5,
"docker_sock_host_root_risk": True,
},
"rootless_podman": {
"architecture_chain": (
"podman CLI -> fork-exec -> conmon -> crun (rootless userns)"
),
"daemon_required": False,
"oci_runtime": "crun",
"network_driver": "pasta / slirp4netns",
"storage_driver": "fuse-overlayfs / rootless userxattr overlay",
"root_uid_on_host": 100000,
"subuid_mapping": "appuser:100000:65536",
"user_ns_isolated": True,
"hardware_vm_isolation": False,
"shared_host_syscalls": 300,
"cold_start_ms": 34.0,
"control_overhead_mib": 2.8,
"docker_sock_host_root_risk": False,
},
"firecracker_microvm": {
"architecture_chain": (
"jailer (chroot/cgroups/seccomp) -> firecracker VMM (Rust) -> "
"KVM (/dev/kvm) -> guest kernel + VirtIO"
),
"daemon_required": False,
"oci_runtime": "firecracker-vmm",
"network_driver": "virtio-net + tap",
"storage_driver": "virtio-block (ext4 rootfs)",
"root_uid_on_host": 10001,
"subuid_mapping": "jailer-uid:10001:1",
"user_ns_isolated": True,
"hardware_vm_isolation": True,
"shared_host_syscalls": 35,
"cold_start_ms": 118.0,
"control_overhead_mib": 4.5,
"docker_sock_host_root_risk": False,
},
}
def evaluate_namespace_isolation(runtime_mode: str = "rootless_podman") -> dict[str, Any]:
"""Evaluate 7 Linux namespaces, pivot_root escape defense, and runtime isolation posture."""
if runtime_mode not in _RUNTIME_PROFILES:
valid = ", ".join(sorted(_RUNTIME_PROFILES))
raise ValueError(f"Unknown runtime_mode {runtime_mode!r}; expected one of: {valid}")
profile = _RUNTIME_PROFILES[runtime_mode]
isolated_ns = list(KERNEL_NAMESPACES)
if not profile["user_ns_isolated"] and "USER" in isolated_ns:
isolated_ns.remove("USER")
inode_map = {
ns: f"{ns.lower()}:[{4026532100 + idx * 17 + (1 if profile['user_ns_isolated'] else 0)}]"
for idx, ns in enumerate(KERNEL_NAMESPACES)
}
return {
"runtime_mode": runtime_mode,
"architecture_chain": profile["architecture_chain"],
"daemon_required": profile["daemon_required"],
"oci_runtime": profile["oci_runtime"],
"network_driver": profile["network_driver"],
"storage_driver": profile["storage_driver"],
"rootfs_isolation_syscall": "pivot_root + umount2(MNT_DETACH)",
"chroot_escape_mitigated": True,
"namespaces_supported": list(KERNEL_NAMESPACES),
"namespaces_isolated": isolated_ns,
"isolated_namespace_count": len(isolated_ns),
"host_proc_ns_inodes": inode_map,
"container_uid0_mapped_to_host_uid": profile["root_uid_on_host"],
"subuid_range": profile["subuid_mapping"],
"hardware_vm_isolation": profile["hardware_vm_isolation"],
"shared_host_syscalls": profile["shared_host_syscalls"],
"cold_start_ms": profile["cold_start_ms"],
"control_overhead_mib": profile["control_overhead_mib"],
"docker_sock_host_root_risk": profile["docker_sock_host_root_risk"],
"untrusted_ai_sandbox_safe": bool(
profile["hardware_vm_isolation"] and not profile["docker_sock_host_root_risk"]
),
}
def simulate_cgroups_v2_throttling_and_oom(
*,
cpu_quota_us: int = 100_000,
cpu_period_us: int = 100_000,
active_threads: int = 8,
host_cores: int = 16,
request_cpu_work_ms: float = 25.0,
memory_current_mb: float = 384.0,
memory_high_mb: float = 420.0,
memory_max_mb: float = 512.0,
pids_current: int = 16,
pids_max: int = 256,
pid1_mode: str = "exec_tini",
sigterm_sent: bool = False,
) -> dict[str, Any]:
"""Simulate cgroups v2 cpu.max CFS throttling, memory.high/max OOM (137), and PID 1 signals."""
if cpu_quota_us <= 0 or cpu_period_us <= 0:
raise ValueError("cpu_quota_us and cpu_period_us must be positive.")
if active_threads <= 0 or host_cores <= 0:
raise ValueError("active_threads and host_cores must be positive.")
if memory_high_mb <= 0 or memory_max_mb < memory_high_mb:
raise ValueError("Require 0 < memory_high_mb <= memory_max_mb.")
if pids_max <= 0:
raise ValueError("pids_max must be positive.")
if pid1_mode not in ("exec_tini", "shell_form"):
raise ValueError("pid1_mode must be 'exec_tini' or 'shell_form'.")
effective_vcpus = cpu_quota_us / cpu_period_us
parallel_threads = min(active_threads, host_cores)
period_ms = cpu_period_us / 1000.0
quota_ms = cpu_quota_us / 1000.0
# Aggregate CFS bandwidth consumed concurrently across parallel_threads
t_exhaust_ms = quota_ms / parallel_threads
burst_wall_if_unthrottled_ms = request_cpu_work_ms / min(
parallel_threads, max(1.0, effective_vcpus)
)
# Simulate 20 requests arriving in bursts over consecutive 100ms CFS periods
n_samples = 40
# Model bursty parallel thread utilization where multi-thread OpenMP burns quota fast
burn_rate_per_ms = float(parallel_threads)
total_cpu_per_req_ms = request_cpu_work_ms * (1.0 + 0.12 * max(0, parallel_threads - 1))
quota_per_period_ms = quota_ms
latencies_ms: list[float] = []
nr_periods = 0
nr_throttled = 0
throttled_usec = 0
for idx in range(n_samples):
# Introduce small deterministic jitter across request payloads
cpu_need_ms = total_cpu_per_req_ms * (0.85 + 0.30 * ((idx * 7) % 11) / 10.0)
wall_ms = 0.0
remaining_cpu = cpu_need_ms
# Start near period start for even requests or mid-period for odd requests
period_budget = quota_per_period_ms * (1.0 if idx % 3 != 2 else 0.45)
while remaining_cpu > 1e-9:
nr_periods += 1
if remaining_cpu <= period_budget:
wall_ms += remaining_cpu / burn_rate_per_ms
remaining_cpu = 0.0
else:
exec_wall = period_budget / burn_rate_per_ms
stall_wall = max(0.0, period_ms - exec_wall)
wall_ms += exec_wall + stall_wall
remaining_cpu -= period_budget
nr_throttled += 1
throttled_usec += round(stall_wall * 1000.0)
period_budget = quota_per_period_ms
latencies_ms.append(wall_ms)
reclaim_throttled = memory_current_mb >= memory_high_mb and memory_current_mb < memory_max_mb
if reclaim_throttled:
# Direct memory reclaim adds latency penalty without killing process
pressure_ratio = (memory_current_mb - memory_high_mb) / max(
1.0, memory_max_mb - memory_high_mb
)
reclaim_penalty_ms = 25.0 + 90.0 * pressure_ratio
latencies_ms = [lat + reclaim_penalty_ms for lat in latencies_ms]
lat_arr = np.asarray(latencies_ms, dtype=np.float64)
p50_ms = float(np.percentile(lat_arr, 50))
p99_ms = float(np.percentile(lat_arr, 99))
oom_killed = memory_current_mb >= memory_max_mb
fork_rejected = pids_current >= pids_max
if oom_killed:
exit_code = 137 # 128 + 9 (SIGKILL by cgroup OOM killer)
termination_reason = "OOMKilled: memory.current >= memory.max -> SIGKILL (128+9)"
elif sigterm_sent:
if pid1_mode == "shell_form":
exit_code = 137 # /bin/sh swallows SIGTERM -> timeout -> SIGKILL
termination_reason = "PID 1 /bin/sh swallowed SIGTERM -> grace timeout SIGKILL (137)"
else:
exit_code = 143 # 128 + 15 (clean SIGTERM handled by exec-form / tini)
termination_reason = "Graceful SIGTERM shutdown handled by PID 1 / tini (128+15)"
else:
exit_code = 0
termination_reason = "Running healthy"
t_stall_ms = max(0.0, period_ms - t_exhaust_ms) if t_exhaust_ms < period_ms else 0.0
throttle_ratio = nr_throttled / max(1, nr_periods)
return {
"cpu_max_setting": f"{cpu_quota_us} {cpu_period_us}",
"effective_vcpus": round(effective_vcpus, 3),
"parallel_threads": parallel_threads,
"t_exhaust_ms": round(t_exhaust_ms, 2),
"t_stall_ms": round(t_stall_ms, 2),
"burst_wall_unthrottled_ms": round(burst_wall_if_unthrottled_ms, 2),
"nr_periods": nr_periods,
"nr_throttled": nr_throttled,
"throttled_usec": throttled_usec,
"throttle_ratio": round(throttle_ratio, 4),
"p50_latency_ms": round(p50_ms, 2),
"p99_latency_ms": round(p99_ms, 2),
"memory_current_mb": round(memory_current_mb, 2),
"memory_high_mb": round(memory_high_mb, 2),
"memory_max_mb": round(memory_max_mb, 2),
"reclaim_throttled": reclaim_throttled,
"oom_killed": oom_killed,
"pids_current": pids_current,
"pids_max": pids_max,
"fork_rejected_eagain": fork_rejected,
"pid1_mode": pid1_mode,
"exit_code": exit_code,
"termination_reason": termination_reason,
}
@dataclass(frozen=True, slots=True)
class OverlayLayerRecord:
layer_id: str
instruction: str
tar_size_mb: float
copied_up_files: tuple[str, ...]
whiteouts_created: tuple[str, ...]
def simulate_overlayfs_cow_and_whiteouts(
*,
base_os_mb: float = 120.0,
weights_mb: float = 800.0,
separate_chmod_chown: bool = True,
delete_weights_in_later_run: bool = False,
) -> dict[str, Any]:
"""Simulate OverlayFS lowerdir/upperdir Copy-on-Write 2W bloat and .wh.* whiteouts."""
if base_os_mb <= 0 or weights_mb <= 0:
raise ValueError("base_os_mb and weights_mb must be positive.")
layers: list[OverlayLayerRecord] = [
OverlayLayerRecord(
layer_id="L0_base",
instruction="FROM python:3.12-slim-bookworm",
tar_size_mb=round(base_os_mb, 2),
copied_up_files=(),
whiteouts_created=(),
),
OverlayLayerRecord(
layer_id="L1_copy_weights",
instruction="COPY model.safetensors /models/model.safetensors",
tar_size_mb=round(weights_mb, 2),
copied_up_files=(),
whiteouts_created=(),
),
]
if separate_chmod_chown:
layers.append(
OverlayLayerRecord(
layer_id="L2_chmod_copyup",
instruction=(
"RUN chmod 0644 /models/model.safetensors "
"&& chown 10001:10001 /models/model.safetensors"
),
tar_size_mb=round(weights_mb, 2),
copied_up_files=("/models/model.safetensors",),
whiteouts_created=(),
)
)
if delete_weights_in_later_run:
layers.append(
OverlayLayerRecord(
layer_id="L3_rm_whiteout",
instruction="RUN rm -f /models/model.safetensors",
tar_size_mb=0.01,
copied_up_files=(),
whiteouts_created=("/models/.wh.model.safetensors",),
)
)
total_image_mb = round(sum(layer.tar_size_mb for layer in layers), 2)
visible_merged_mb = round(base_os_mb + (0.0 if delete_weights_in_later_run else weights_mb), 2)
wasted_cow_mb = round(total_image_mb - visible_merged_mb, 2)
return {
"lowerdir_layers": [layer.layer_id for layer in layers],
"separate_chmod_chown": separate_chmod_chown,
"delete_weights_in_later_run": delete_weights_in_later_run,
"total_oci_image_mb": total_image_mb,
"visible_merged_rootfs_mb": visible_merged_mb,
"wasted_cow_and_deleted_mb": wasted_cow_mb,
"amplification_factor_on_weights": round(
(total_image_mb - base_os_mb) / weights_mb, 2
),
"whiteout_markers": [w for layer in layers for w in layer.whiteouts_created],
"layers": [
{
"layer_id": layer.layer_id,
"instruction": layer.instruction,
"tar_size_mb": layer.tar_size_mb,
"copied_up_files": list(layer.copied_up_files),
"whiteouts_created": list(layer.whiteouts_created),
}
for layer in layers
],
}
def simulate_buildkit_layer_cache(
*,
n_source_commits: int = 10,
deps_mb: float = 420.0,
source_mb: float = 4.0,
base_os_mb: float = 120.0,
cold_deps_download_s: float = 65.0,
cold_uv_deps_s: float = 16.0,
) -> dict[str, Any]:
"""Compare legacy COPY-early pip rebuilds vs BuildKit lockfile-split uv cache mounts."""
if n_source_commits < 1:
raise ValueError("n_source_commits must be >= 1.")
# Legacy pattern: COPY . /app before pip install -> every source commit busts deps layer
legacy_total_s = 0.0
legacy_net_mb = 0.0
legacy_cache_hits = 0
legacy_total_layers = n_source_commits * 3 # base + copy + pip_install
for idx in range(n_source_commits):
# Commit 0 pulls base OS (120 MB); commits 1..N-1 hit base OS but miss COPY & pip!
if idx == 0:
legacy_net_mb += base_os_mb + deps_mb
legacy_total_s += 8.0 + cold_deps_download_s + 2.5
else:
legacy_cache_hits += 1 # only base OS layer cached
legacy_net_mb += deps_mb # pip --no-cache-dir re-downloads wheels
legacy_total_s += cold_deps_download_s + 2.5
# BuildKit + uv pattern: bind-mount pyproject.toml/uv.lock + --mount=type=cache BEFORE COPY src/
buildkit_total_s = 0.0
buildkit_net_mb = 0.0
buildkit_cache_hits = 0
buildkit_total_layers = n_source_commits * 3 # base + deps_sync + copy_src_editable
for idx in range(n_source_commits):
if idx == 0:
buildkit_net_mb += base_os_mb + deps_mb
buildkit_total_s += 6.0 + cold_uv_deps_s + 1.8
else:
buildkit_cache_hits += 2 # base + deps_sync both hit! only COPY src/ runs
buildkit_net_mb += 0.0
buildkit_total_s += 1.4
_ = source_mb # explicitly accounted as tiny layer delta
legacy_hit_rate = legacy_cache_hits / legacy_total_layers
buildkit_hit_rate = buildkit_cache_hits / buildkit_total_layers
speedup_x = legacy_total_s / max(0.1, buildkit_total_s)
return {
"n_source_commits": n_source_commits,
"legacy_copy_early": {
"cache_hit_rate": round(legacy_hit_rate, 3),
"avg_rebuild_s": round(legacy_total_s / n_source_commits, 2),
"total_ci_build_s": round(legacy_total_s, 2),
"network_downloaded_mb": round(legacy_net_mb, 2),
},
"buildkit_uv_split": {
"cache_hit_rate": round(buildkit_hit_rate, 3),
"avg_rebuild_s": round(buildkit_total_s / n_source_commits, 2),
"total_ci_build_s": round(buildkit_total_s, 2),
"network_downloaded_mb": round(buildkit_net_mb, 2),
},
"ci_build_speedup_x": round(speedup_x, 2),
"network_bandwidth_saved_mb": round(legacy_net_mb - buildkit_net_mb, 2),
}
def _sha256_blob_digest(payload: str) -> str:
return f"sha256:{hashlib.sha256(payload.encode('utf-8')).hexdigest()}"
def simulate_oci_registry_deduplication(
*,
num_releases: int = 6,
base_os_mb: float = 85.0,
ml_runtime_mb: float = 1150.0,
app_layer_mb: float = 8.5,
) -> dict[str, Any]:
"""Simulate Harbor/OCI Distribution v2 content-addressable sha256 blob deduplication."""
if num_releases < 1:
raise ValueError("num_releases must be >= 1.")
shared_base_digest = _sha256_blob_digest("python:3.12-slim-bookworm-base")
shared_ml_digest = _sha256_blob_digest("torch-2.6-numpy-fastapi-deps-v1")
unique_blobs: dict[str, float] = {}
manifests: list[dict[str, Any]] = []
raw_total_mb = 0.0
for idx in range(num_releases):
tag = f"v1.0.{idx}"
app_digest = _sha256_blob_digest(f"app-src-commit-{idx}")
# Releases 0..2 share ml_runtime v1; releases 3..5 bump app layer only (or reuse runtime)
blobs = [
(shared_base_digest, base_os_mb),
(shared_ml_digest, ml_runtime_mb),
(app_digest, app_layer_mb),
]
# Compute OCI ChainID for bottom->top diff verification
chain_id = blobs[0][0]
for digest, _ in blobs[1:]:
chain_id = _sha256_blob_digest(f"{chain_id} {digest}")
for digest, size_mb in blobs:
unique_blobs[digest] = size_mb
raw_total_mb += size_mb
manifests.append(
{
"tag": tag,
"pinned_ref": f"harbor.internal/ml/serving@{_sha256_blob_digest(chain_id)[:24]}...",
"chain_id": chain_id[:24] + "...",
"layer_digests": [d[:19] + "..." for d, _ in blobs],
}
)
unique_stored_mb = round(sum(unique_blobs.values()), 2)
raw_total_mb = round(raw_total_mb, 2)
dedup_savings_mb = round(raw_total_mb - unique_stored_mb, 2)
dedup_savings_pct = round((dedup_savings_mb / max(1e-6, raw_total_mb)) * 100.0, 2)
naive_push_transfers = num_releases * 3
actual_blob_uploads = len(unique_blobs)
return {
"num_releases": num_releases,
"raw_cumulative_mb": raw_total_mb,
"unique_stored_mb": unique_stored_mb,
"dedup_savings_mb": dedup_savings_mb,
"dedup_savings_pct": dedup_savings_pct,
"naive_layer_uploads": naive_push_transfers,
"actual_unique_blob_uploads": actual_blob_uploads,
"head_dedup_skip_count": naive_push_transfers - actual_blob_uploads,
"sample_manifests": manifests[:3],
}
def compute_combined_risk_index(
throttling_result: dict[str, Any],
overlay_result: dict[str, Any],
) -> float:
"""Compute normalized [0..100] operational risk penalty for container runtime settings."""
throttle_pen = min(40.0, float(throttling_result["throttle_ratio"]) * 50.0)
oom_pen = 45.0 if throttling_result["oom_killed"] else (
15.0 if throttling_result["reclaim_throttled"] else 0.0
)
bloat_pen = min(15.0, float(overlay_result["amplification_factor_on_weights"]) * 5.0 - 5.0)
score = max(0.0, 100.0 - throttle_pen - oom_pen - max(0.0, bloat_pen))
return round(math.fsum([score]), 2)
"""Real Dockerfile, .dockerignore, and PyYAML docker-compose.yml parser and security auditor."""
from __future__ import annotations
import re
from collections import deque
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import yaml
_SECRET_VAR_RE = re.compile(r"(TOKEN|SECRET|PASSWORD|API_KEY|PRIVATE_KEY|ACCESS_KEY)", re.I)
_DIGEST_PIN_RE = re.compile(r"@sha256:[0-9a-f]{64}\b", re.I)
_LATEST_TAG_RE = re.compile(r"^([^\s:@]+(?:/[^\s:@]+)*):latest\b", re.I)
_CHMOD_CHOWN_RE = re.compile(r"\b(chmod|chown)\b", re.I)
@dataclass(frozen=True, slots=True)
class AuditFinding:
rule_id: str
severity: str
penalty: int
message: str
def _parse_dockerfile_instructions(dockerfile_text: str) -> list[tuple[int, str, str]]:
"""Collapse backslash-continued lines into (line_no, OPCODE, args) records."""
instructions: list[tuple[int, str, str]] = []
buf: list[str] = []
start_line = 0
for lineno, raw_line in enumerate(dockerfile_text.splitlines(), start=1):
stripped = raw_line.strip()
if not buf and (not stripped or stripped.startswith("#")):
continue
if not buf:
start_line = lineno
if stripped.endswith("\\"):
buf.append(stripped[:-1].rstrip())
continue
buf.append(stripped)
full_stmt = " ".join(part for part in buf if part).strip()
buf.clear()
if not full_stmt or full_stmt.startswith("#"):
continue
parts = full_stmt.split(None, 1)
opcode = parts[0].upper()
args = parts[1].strip() if len(parts) > 1 else ""
instructions.append((start_line, opcode, args))
if buf:
full_stmt = " ".join(buf).strip()
parts = full_stmt.split(None, 1)
instructions.append((start_line, parts[0].upper(), parts[1].strip() if len(parts) > 1 else ""))
return instructions
def _audit_dockerignore(dockerignore_path: Path | None) -> tuple[bool, list[str]]:
if dockerignore_path is None or not dockerignore_path.is_file():
return False, []
patterns = [
line.strip()
for line in dockerignore_path.read_text(encoding="utf-8").splitlines()
if line.strip() and not line.strip().startswith("#")
]
return True, patterns
def audit_dockerfile(
dockerfile_path: Path,
dockerignore_path: Path | None = None,
) -> dict[str, Any]:
"""Parse and quantitatively score a real Dockerfile + .dockerignore against 2026 standards."""
if not dockerfile_path.is_file():
raise FileNotFoundError(f"Dockerfile not found: {dockerfile_path}")
raw_text = dockerfile_path.read_text(encoding="utf-8")
instructions = _parse_dockerfile_instructions(raw_text)
has_ignore, ignore_patterns = _audit_dockerignore(dockerignore_path)
from_stages = [(ln, args) for ln, op, args in instructions if op == "FROM"]
is_multistage = len(from_stages) >= 2
final_from_args = from_stages[-1][1] if from_stages else ""
findings: list[AuditFinding] = []
score = 100
def _penalize(rule_id: str, severity: str, penalty: int, message: str) -> None:
nonlocal score
score = max(0, score - penalty)
findings.append(
AuditFinding(rule_id=rule_id, severity=severity, penalty=penalty, message=message)
)
# 1. Multi-stage & base image pinning check
if not is_multistage:
_penalize(
"DF001_SINGLE_STAGE",
"HIGH",
15,
"Single-stage build ships build/package toolchains into production image.",
)
base_ref = final_from_args.split()[0] if final_from_args else ""
has_pinned_digest = bool(_DIGEST_PIN_RE.search(base_ref))
uses_latest = bool(_LATEST_TAG_RE.search(base_ref)) or (
":" not in base_ref and "@sha256:" not in base_ref and bool(base_ref)
)
if uses_latest:
_penalize(
"DF002_MUTABLE_LATEST_TAG",
"HIGH",
12,
f"Final FROM image {base_ref!r} uses mutable :latest/untagged reference.",
)
elif not has_pinned_digest:
_penalize(
"DF003_UNPINNED_DIGEST",
"MEDIUM",
6,
f"Final FROM image {base_ref!r} lacks immutable @sha256: digest pin.",
)
# 2. Secrets in ARG / ENV
secret_leaks: list[str] = []
for ln, op, args in instructions:
if op in ("ARG", "ENV") and _SECRET_VAR_RE.search(args):
secret_leaks.append(f"L{ln}:{op} {args.split('=', 1)[0]}")
if secret_leaks:
_penalize(
"DF004_SECRET_IN_ARG_ENV",
"CRITICAL",
22,
f"Credentials in ARG/ENV bake secrets into OCI config/history: {secret_leaks}",
)
# 3. Copy-early cache busting & BuildKit cache/uv usage
install_idx: int | None = None
broad_copy_idx: int | None = None
uses_buildkit_cache = False
for idx, (_ln, op, args) in enumerate(instructions):
if op == "COPY" and re.search(r"(?:^|\s)\.\s+", args) and broad_copy_idx is None:
broad_copy_idx = idx
if op == "RUN" and ("pip install" in args or "uv sync" in args):
if install_idx is None:
install_idx = idx
if "--mount=type=cache" in args:
uses_buildkit_cache = True
if broad_copy_idx is not None and install_idx is not None and broad_copy_idx < install_idx:
_penalize(
"DF005_COPY_BEFORE_DEPS",
"HIGH",
14,
"Broad `COPY .` precedes dependency installation, busting cache on every edit.",
)
if not uses_buildkit_cache:
_penalize(
"DF006_NO_BUILDKIT_CACHE_MOUNT",
"MEDIUM",
8,
"Missing BuildKit `--mount=type=cache` for uv/pip dependency caching.",
)
# 4. Separate RUN chmod/chown copy-up bloat
copy_indices = [idx for idx, (_ln, op, _args) in enumerate(instructions) if op == "COPY"]
separate_chmod_runs = [
ln
for idx, (ln, op, args) in enumerate(instructions)
if op == "RUN"
and _CHMOD_CHOWN_RE.search(args)
and any(c_idx < idx for c_idx in copy_indices)
and "groupadd" not in args
and "useradd" not in args
]
if separate_chmod_runs:
_penalize(
"DF007_OVERLAYFS_CHOWN_COPYUP",
"HIGH",
12,
f"Separate RUN chmod/chown at lines {separate_chmod_runs} causes 2x OverlayFS copy-up.",
)
# 5. Non-root USER check (inspect final stage)
final_stage_start = max(
(idx for idx, (_ln, op, _a) in enumerate(instructions) if op == "FROM"),
default=0,
)
final_insts = instructions[final_stage_start:]
user_insts = [args for _ln, op, args in final_insts if op == "USER"]
non_root_user = bool(user_insts and not user_insts[-1].strip().startswith(("0", "root")))
if not non_root_user:
_penalize(
"DF008_ROOT_USER",
"CRITICAL",
18,
"Final runtime container runs as root (UID 0); specify unprivileged USER >= 10001.",
)
# 6. Exec-form CMD/ENTRYPOINT + STOPSIGNAL + HEALTHCHECK
cmd_or_entry = [args for _ln, op, args in final_insts if op in ("CMD", "ENTRYPOINT")]
exec_form_entrypoint = bool(cmd_or_entry and cmd_or_entry[-1].lstrip().startswith("["))
if not exec_form_entrypoint:
_penalize(
"DF009_SHELL_FORM_PID1",
"HIGH",
12,
"Shell-form CMD/ENTRYPOINT runs /bin/sh as PID 1 and swallows SIGTERM (-> Exit 137).",
)
has_healthcheck = any(op == "HEALTHCHECK" for _ln, op, _args in final_insts)
if not has_healthcheck:
_penalize(
"DF010_MISSING_HEALTHCHECK",
"MEDIUM",
6,
"Missing Dockerfile HEALTHCHECK instruction.",
)
has_stopsignal = any(op == "STOPSIGNAL" for _ln, op, _args in final_insts)
if not has_stopsignal:
_penalize(
"DF011_MISSING_STOPSIGNAL",
"LOW",
3,
"Explicit `STOPSIGNAL SIGTERM` not declared.",
)
# 7. .dockerignore coverage
required_ignore_tokens = (".git", ".env", "__pycache__", ".venv")
ignore_ok = has_ignore and all(
any(tok in pat for pat in ignore_patterns) for tok in required_ignore_tokens
)
if not ignore_ok:
_penalize(
"DF012_WEAK_OR_MISSING_DOCKERIGNORE",
"MEDIUM",
8,
".dockerignore missing or fails to exclude .git, .env, .venv, and __pycache__.",
)
# Estimate projected OCI image footprint (MB)
projected_mb = 155.0 if is_multistage else 980.0
if "slim" in base_ref:
projected_mb = 175.0 if is_multistage else 420.0
if "wolfi" in base_ref or "distroless" in base_ref:
projected_mb = 68.0
if separate_chmod_runs:
projected_mb += 180.0
if not ignore_ok:
projected_mb += 95.0
return {
"dockerfile": dockerfile_path.name,
"instruction_count": len(instructions),
"stage_count": len(from_stages),
"is_multistage": is_multistage,
"final_base_image": base_ref,
"has_pinned_sha256_digest": has_pinned_digest,
"uses_mutable_latest": uses_latest,
"secret_leaks_detected": secret_leaks,
"uses_buildkit_cache_mount": uses_buildkit_cache,
"copy_before_install_trap": (
broad_copy_idx is not None and install_idx is not None and broad_copy_idx < install_idx
),
"separate_chmod_copyup_trap": bool(separate_chmod_runs),
"non_root_user": non_root_user,
"exec_form_pid1": exec_form_entrypoint,
"has_healthcheck": has_healthcheck,
"has_stopsignal": has_stopsignal,
"dockerignore_hardened": ignore_ok,
"projected_image_mb": round(projected_mb, 1),
"security_score": score,
"grade": "HARDENED" if score >= 90 else ("WARNING" if score >= 65 else "INSECURE"),
"findings": [
{
"rule_id": f.rule_id,
"severity": f.severity,
"penalty": f.penalty,
"message": f.message,
}
for f in findings
],
}
def _topological_sort_services(services: dict[str, Any]) -> list[str]:
"""Compute deterministic startup order from depends_on dependencies via Kahn's algorithm."""
deps_map: dict[str, set[str]] = {}
dependents: dict[str, set[str]] = {name: set() for name in services}
for svc_name, cfg in services.items():
raw_deps = cfg.get("depends_on") or {}
if isinstance(raw_deps, list):
svc_deps = {str(d) for d in raw_deps}
elif isinstance(raw_deps, dict):
svc_deps = {str(d) for d in raw_deps}
else:
svc_deps = set()
unknown = svc_deps - set(services)
if unknown:
raise ValueError(f"Service {svc_name!r} depends on undefined services: {sorted(unknown)}")
deps_map[svc_name] = svc_deps
for dep in svc_deps:
dependents[dep].add(svc_name)
in_degree = {name: len(deps_map[name]) for name in services}
queue: deque[str] = deque(sorted(name for name, deg in in_degree.items() if deg == 0))
boot_order: list[str] = []
while queue:
cur = queue.popleft()
boot_order.append(cur)
for nxt in sorted(dependents[cur]):
in_degree[nxt] -= 1
if in_degree[nxt] == 0:
queue.append(nxt)
if len(boot_order) != len(services):
raise ValueError("Cycle detected in docker-compose depends_on graph.")
return boot_order
def analyze_compose_stack(compose_path: Path) -> dict[str, Any]:
"""Parse real docker-compose.yml via PyYAML and verify DAG boot order, networks & hardening."""
if not compose_path.is_file():
raise FileNotFoundError(f"Compose file not found: {compose_path}")
parsed = yaml.safe_load(compose_path.read_text(encoding="utf-8"))
if not isinstance(parsed, dict) or "services" not in parsed:
raise ValueError("Invalid Compose specification: top-level 'services' mapping required.")
services: dict[str, Any] = parsed.get("services") or {}
networks_cfg: dict[str, Any] = parsed.get("networks") or {}
volumes_cfg: dict[str, Any] = parsed.get("volumes") or {}
boot_order = _topological_sort_services(services)
internal_networks = {
net_name
for net_name, net_body in networks_cfg.items()
if isinstance(net_body, dict) and bool(net_body.get("internal", False))
}
service_reports: dict[str, dict[str, Any]] = {}
healthy_edges: list[dict[str, str]] = []
for svc_name, cfg in services.items():
raw_nets = cfg.get("networks") or []
svc_nets = list(raw_nets.keys()) if isinstance(raw_nets, dict) else [str(n) for n in raw_nets]
exposed_ports = [str(p) for p in (cfg.get("ports") or [])]
egress_isolated = bool(svc_nets) and all(n in internal_networks for n in svc_nets)
raw_deps = cfg.get("depends_on") or {}
if isinstance(raw_deps, dict):
for dep_name, dep_cfg in raw_deps.items():
cond = (
dep_cfg.get("condition", "service_started")
if isinstance(dep_cfg, dict)
else "service_started"
)
healthy_edges.append(
{"from": str(dep_name), "to": svc_name, "condition": str(cond)}
)
cap_drop = [str(c).upper() for c in (cfg.get("cap_drop") or [])]
sec_opt = [str(s) for s in (cfg.get("security_opt") or [])]
limits = ((cfg.get("deploy") or {}).get("resources") or {}).get("limits") or {}
service_reports[svc_name] = {
"networks": svc_nets,
"egress_isolated_internal_only": egress_isolated,
"exposed_host_ports": exposed_ports,
"has_healthcheck": isinstance(cfg.get("healthcheck"), dict),
"read_only_rootfs": bool(cfg.get("read_only", False)),
"has_tmpfs": bool(cfg.get("tmpfs")),
"drops_all_caps": "ALL" in cap_drop,
"no_new_privileges": "no-new-privileges:true" in sec_opt,
"resource_limits": limits,
"uses_init": bool(cfg.get("init", False)),
}
# Verify network segmentation: data-tier services share backend with api and stay off frontend
data_services_isolated = all(
service_reports[name]["egress_isolated_internal_only"]
and service_reports[name]["exposed_host_ports"] == []
for name in ("postgres", "redis")
if name in service_reports
)
all_healthy_deps = bool(healthy_edges) and all(
edge["condition"] == "service_healthy" for edge in healthy_edges
)
return {
"compose_file": compose_path.name,
"service_count": len(services),
"boot_order": boot_order,
"dependency_edges": healthy_edges,
"all_depends_use_service_healthy": all_healthy_deps,
"networks": {
name: {
"driver": (cfg or {}).get("driver", "bridge"),
"internal": bool((cfg or {}).get("internal", False)),
}
for name, cfg in networks_cfg.items()
},
"named_volumes": sorted(volumes_cfg.keys()),
"data_services_egress_isolated": data_services_isolated,
"services": service_reports,
}
"""FastAPI containerized service matching Lab 05 Dockerfile entrypoint & Compose probes."""
from __future__ import annotations
import json
import sys
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field
from container_ops_lab.container_audit_and_compose import (
analyze_compose_stack,
audit_dockerfile,
)
from container_ops_lab.linux_isolation_sim import (
compute_combined_risk_index,
simulate_cgroups_v2_throttling_and_oom,
simulate_overlayfs_cow_and_whiteouts,
)
LAB_ROOT = Path(__file__).resolve().parents[2]
class ContainerScoreRequest(BaseModel):
"""Strict Pydantic v2 payload evaluating cgroups v2 and OverlayFS operational posture."""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False)
workload_name: str = Field(min_length=2, max_length=64)
cpu_quota_vcpus: float = Field(gt=0.0, le=64.0)
omp_threads: int = Field(ge=1, le=128)
rss_mb: float = Field(gt=0.0, le=65536.0)
memory_max_mb: float = Field(ge=64.0, le=65536.0)
weights_mb: float = Field(gt=0.0, le=32768.0)
separate_chown: bool = False
@dataclass(slots=True)
class ContainerAppState:
lifespan_started: bool = False
lifespan_stopped: bool = False
degraded: bool = False
draining: bool = False
dockerfile_path: Path | None = None
dockerfile_naive_path: Path | None = None
dockerignore_path: Path | None = None
compose_path: Path | None = None
cached_stack_status: dict[str, Any] | None = None
def _build_stack_snapshot(state: ContainerAppState) -> dict[str, Any]:
hardened_audit = (
audit_dockerfile(state.dockerfile_path, state.dockerignore_path)
if state.dockerfile_path and state.dockerfile_path.is_file()
else None
)
naive_audit = (
audit_dockerfile(state.dockerfile_naive_path, None)
if state.dockerfile_naive_path and state.dockerfile_naive_path.is_file()
else None
)
compose_summary = (
analyze_compose_stack(state.compose_path)
if state.compose_path and state.compose_path.is_file()
else None
)
return {
"hardened_dockerfile": hardened_audit,
"naive_dockerfile": naive_audit,
"compose_stack": compose_summary,
}
def create_container_app(
*,
dockerfile_path: Path | None = None,
dockerfile_naive_path: Path | None = None,
dockerignore_path: Path | None = None,
compose_path: Path | None = None,
) -> FastAPI:
"""Create the containerized FastAPI service inspected by Docker HEALTHCHECK & httpx ASGI."""
default_df = dockerfile_path or (LAB_ROOT / "Dockerfile")
default_naive = dockerfile_naive_path or (LAB_ROOT / "Dockerfile.naive")
default_ignore = dockerignore_path or (LAB_ROOT / ".dockerignore")
default_compose = compose_path or (LAB_ROOT / "docker-compose.yml")
runtime = ContainerAppState(
dockerfile_path=default_df if default_df.is_file() else None,
dockerfile_naive_path=default_naive if default_naive.is_file() else None,
dockerignore_path=default_ignore if default_ignore.is_file() else None,
compose_path=default_compose if default_compose.is_file() else None,
)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
runtime.lifespan_started = True
runtime.cached_stack_status = _build_stack_snapshot(runtime)
yield
runtime.lifespan_stopped = True
app = FastAPI(
title="FSDS Lab 05 Container Ops Service",
version="0.1.0",
lifespan=lifespan,
)
app.state.runtime = runtime
@app.exception_handler(RequestValidationError)
async def validation_problem_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
return JSONResponse(
status_code=422,
media_type="application/problem+json",
content={
"type": "https://fsds.example/problems/container-score-validation",
"title": "Invalid Container Evaluation Request",
"status": 422,
"detail": "Payload failed strict Pydantic v2 schema validation.",
"instance": str(request.url.path),
"errors": [
{"loc": list(err.get("loc", ())), "msg": str(err.get("msg", ""))}
for err in exc.errors()
],
},
)
@app.get("/health/live")
async def health_live() -> dict[str, Any]:
return {"status": "alive", "pid1_signal_ready": True}
@app.get("/health/ready")
async def health_ready() -> JSONResponse:
if runtime.degraded or runtime.draining:
return JSONResponse(
status_code=503,
media_type="application/problem+json",
content={
"type": "https://fsds.example/problems/not-ready",
"title": "Service Not Ready",
"status": 503,
"detail": "Downstream dependency degraded or pod is draining SIGTERM.",
},
)
return JSONResponse(
status_code=200,
content={
"status": "ready",
"postgres_backend": "internal-dns:postgres:5432",
"redis_backend": "internal-dns:redis:6379",
},
)
@app.post("/v1/container-score")
async def score_container_posture(body: ContainerScoreRequest) -> dict[str, Any]:
quota_us = max(10_000, round(body.cpu_quota_vcpus * 100_000))
cg = simulate_cgroups_v2_throttling_and_oom(
cpu_quota_us=quota_us,
cpu_period_us=100_000,
active_threads=body.omp_threads,
memory_current_mb=body.rss_mb,
memory_high_mb=round(body.memory_max_mb * 0.85, 2),
memory_max_mb=body.memory_max_mb,
pid1_mode="exec_tini",
)
ov = simulate_overlayfs_cow_and_whiteouts(
weights_mb=body.weights_mb,
separate_chmod_chown=body.separate_chown,
)
posture_score = compute_combined_risk_index(cg, ov)
return {
"workload_name": body.workload_name,
"posture_score": posture_score,
"throttle_ratio": cg["throttle_ratio"],
"p99_latency_ms": cg["p99_latency_ms"],
"oom_killed": cg["oom_killed"],
"exit_code_predicted": cg["exit_code"],
"total_oci_image_mb": ov["total_oci_image_mb"],
"wasted_cow_mb": ov["wasted_cow_and_deleted_mb"],
}
@app.get("/v1/stack-status")
async def stack_status() -> dict[str, Any]:
if runtime.cached_stack_status is None:
runtime.cached_stack_status = _build_stack_snapshot(runtime)
return runtime.cached_stack_status
return app
def main() -> None:
"""CLI entrypoint printing live stack audit status or running ASGI smoke check."""
if "--print-stack" in sys.argv:
state = ContainerAppState(
dockerfile_path=LAB_ROOT / "Dockerfile",
dockerfile_naive_path=LAB_ROOT / "Dockerfile.naive",
dockerignore_path=LAB_ROOT / ".dockerignore",
compose_path=LAB_ROOT / "docker-compose.yml",
)
print(json.dumps(_build_stack_snapshot(state), indent=2))
return
import uvicorn
uvicorn.run(
"container_ops_lab.app:create_container_app",
factory=True,
host="127.0.0.1",
port=8000,
)
if __name__ == "__main__":
main()
"""End-to-end CLI benchmark & container audit runner for FSDS-SOTA-2026 Track 2 Lab 05."""
from __future__ import annotations
import argparse
import asyncio
import json
import sys
from pathlib import Path
from typing import Any
import httpx
LAB_ROOT = Path(__file__).resolve().parents[1]
SRC_DIR = LAB_ROOT / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
from container_ops_lab.app import create_container_app # noqa: E402
from container_ops_lab.container_audit_and_compose import ( # noqa: E402
analyze_compose_stack,
audit_dockerfile,
)
from container_ops_lab.linux_isolation_sim import ( # noqa: E402
evaluate_namespace_isolation,
simulate_buildkit_layer_cache,
simulate_cgroups_v2_throttling_and_oom,
simulate_oci_registry_deduplication,
simulate_overlayfs_cow_and_whiteouts,
)
async def _verify_asgi_container_app() -> dict[str, Any]:
"""Verify FastAPI container entrypoint in-process via httpx.ASGITransport (100% offline)."""
app = create_container_app()
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://container-lab",
) as client:
live = await client.get("/health/live")
ready = await client.get("/health/ready")
score_ok = await client.post(
"/v1/container-score",
json={
"workload_name": "inference-v1",
"cpu_quota_vcpus": 1.0,
"omp_threads": 2,
"rss_mb": 340.0,
"memory_max_mb": 512.0,
"weights_mb": 800.0,
"separate_chown": False,
},
)
score_bad = await client.post(
"/v1/container-score",
json={
"workload_name": "bad",
"cpu_quota_vcpus": "1.0",
"omp_threads": 2,
"rss_mb": 100.0,
"memory_max_mb": 512.0,
"weights_mb": 100.0,
"rogue_extra": True,
},
)
stack = await client.get("/v1/stack-status")
return {
"live_status": live.status_code,
"ready_status": ready.status_code,
"score_ok_status": score_ok.status_code,
"score_ok_posture": score_ok.json()["posture_score"],
"score_422_status": score_bad.status_code,
"score_422_media_type": score_bad.headers.get("content-type"),
"stack_boot_order": stack.json()["compose_stack"]["boot_order"],
}
def run_all_container_benchmarks(*, quick: bool = False) -> dict[str, Any]:
"""Run all Linux isolation, OverlayFS, BuildKit, OCI dedup, Dockerfile & Compose checks."""
ns_docker = evaluate_namespace_isolation("rootful_docker")
ns_podman = evaluate_namespace_isolation("rootless_podman")
ns_firecracker = evaluate_namespace_isolation("firecracker_microvm")
cg_pinned = simulate_cgroups_v2_throttling_and_oom(
cpu_quota_us=100_000,
cpu_period_us=100_000,
active_threads=2,
request_cpu_work_ms=25.0,
memory_current_mb=340.0,
memory_high_mb=420.0,
memory_max_mb=512.0,
pid1_mode="exec_tini",
sigterm_sent=True,
)
cg_burst_trap = simulate_cgroups_v2_throttling_and_oom(
cpu_quota_us=100_000,
cpu_period_us=100_000,
active_threads=16,
request_cpu_work_ms=25.0,
memory_current_mb=470.0,
memory_high_mb=420.0,
memory_max_mb=512.0,
pid1_mode="shell_form",
sigterm_sent=True,
)
cg_oom_kill = simulate_cgroups_v2_throttling_and_oom(
cpu_quota_us=100_000,
cpu_period_us=100_000,
active_threads=4,
request_cpu_work_ms=25.0,
memory_current_mb=520.0,
memory_high_mb=420.0,
memory_max_mb=512.0,
pid1_mode="exec_tini",
sigterm_sent=False,
)
ov_inline = simulate_overlayfs_cow_and_whiteouts(
base_os_mb=120.0, weights_mb=800.0, separate_chmod_chown=False, delete_weights_in_later_run=False
)
ov_copyup = simulate_overlayfs_cow_and_whiteouts(
base_os_mb=120.0, weights_mb=800.0, separate_chmod_chown=True, delete_weights_in_later_run=False
)
ov_whiteout = simulate_overlayfs_cow_and_whiteouts(
base_os_mb=120.0, weights_mb=800.0, separate_chmod_chown=True, delete_weights_in_later_run=True
)
buildkit_bench = simulate_buildkit_layer_cache(
n_source_commits=5 if quick else 10,
deps_mb=420.0,
)
oci_dedup = simulate_oci_registry_deduplication(
num_releases=4 if quick else 6,
base_os_mb=85.0,
ml_runtime_mb=1150.0,
app_layer_mb=8.5,
)
df_hardened = audit_dockerfile(LAB_ROOT / "Dockerfile", LAB_ROOT / ".dockerignore")
df_naive = audit_dockerfile(LAB_ROOT / "Dockerfile.naive", None)
compose_audit = analyze_compose_stack(LAB_ROOT / "docker-compose.yml")
asgi_smoke = asyncio.run(_verify_asgi_container_app())
p99_ratio = round(cg_burst_trap["p99_latency_ms"] / max(0.1, cg_pinned["p99_latency_ms"]), 2)
kpis = [
{
"id": "kpi_dockerfile_hardening_score",
"label": "Dockerfile Hardened vs Naive Audit",
"value": f"{df_hardened['security_score']} vs {df_naive['security_score']}/100",
"unit": f"{df_hardened['projected_image_mb']} vs {df_naive['projected_image_mb']} MB",
"status": "ok",
"detail": (
f"Multi-stage + uv + USER 10001 + exec CMD + HEALTHCHECK + @sha256: pin; "
f"naive leaks {len(df_naive['secret_leaks_detected'])} secrets & uses 2x copy-up."
),
},
{
"id": "kpi_cgroups_v2_cfs_and_exit_codes",
"label": "cgroups v2 CFS Burst Trap vs Pinned OMP",
"value": f"{cg_pinned['p99_latency_ms']} vs {cg_burst_trap['p99_latency_ms']} ms p99",
"unit": f"{p99_ratio}x p99 spike",
"status": "warn",
"detail": (
f"16 threads exhaust 100ms quota in {cg_burst_trap['t_exhaust_ms']} ms then stall "
f"{cg_burst_trap['t_stall_ms']} ms; OOM/shell-CMD->Exit {cg_oom_kill['exit_code']} vs "
f"tini->{cg_pinned['exit_code']}."
),
},
{
"id": "kpi_overlayfs_2w_copyup",
"label": "OverlayFS CoW (Inline vs Separate chmod)",
"value": (
f"{ov_inline['total_oci_image_mb']:.0f} vs "
f"{ov_copyup['total_oci_image_mb']:.0f} MB"
),
"unit": f"{ov_copyup['amplification_factor_on_weights']}x weights",
"status": "ok",
"detail": (
f"Separate RUN chmod duplicates 800 MB weights via upperdir copy-up "
f"(+{ov_copyup['wasted_cow_and_deleted_mb']:.0f} MB); later rm leaves .wh. marker "
f"({ov_whiteout['total_oci_image_mb']:.0f} MB)."
),
},
{
"id": "kpi_buildkit_uv_layer_cache",
"label": f"BuildKit uv Split Cache ({buildkit_bench['n_source_commits']} Commits)",
"value": (
f"{buildkit_bench['legacy_copy_early']['avg_rebuild_s']}s -> "
f"{buildkit_bench['buildkit_uv_split']['avg_rebuild_s']}s"
),
"unit": f"{buildkit_bench['ci_build_speedup_x']}x faster",
"status": "ok",
"detail": (
f"Cache hit rate {buildkit_bench['legacy_copy_early']['cache_hit_rate']*100:.1f}% -> "
f"{buildkit_bench['buildkit_uv_split']['cache_hit_rate']*100:.1f}%; "
f"saved {buildkit_bench['network_bandwidth_saved_mb']:.0f} MB wheel pulls."
),
},
{
"id": "kpi_oci_registry_dedup",
"label": f"Harbor OCI sha256 Blob Deduplication ({oci_dedup['num_releases']} Tags)",
"value": f"{oci_dedup['raw_cumulative_mb']:.0f} -> {oci_dedup['unique_stored_mb']:.0f} MB",
"unit": f"-{oci_dedup['dedup_savings_pct']}% storage",
"status": "ok",
"detail": (
f"Content-addressable HEAD skip avoided {oci_dedup['head_dedup_skip_count']}/"
f"{oci_dedup['naive_layer_uploads']} redundant multi-GB layer uploads."
),
},
{
"id": "kpi_compose_internal_and_asgi",
"label": "Compose Boot DAG & internal:true Isolation",
"value": " -> ".join(compose_audit["boot_order"]),
"unit": "0 DB host ports",
"status": "ok",
"detail": (
f"service_healthy={compose_audit['all_depends_use_service_healthy']}, "
f"data_isolated={compose_audit['data_services_egress_isolated']}, "
f"ASGI live={asgi_smoke['live_status']}/ready={asgi_smoke['ready_status']}."
),
},
]
bars = [
{
"id": "bar_cgroups_v2_cfs_p99_ms",
"title": "cgroups v2 cpu.max=100ms: Pinned OMP=2 vs Unpinned 16-Thread Burst p99 (ms)",
"metric_label": "Latency (ms)",
"items": [
{
"label": "pinned_omp_2_threads_p50",
"value": cg_pinned["p50_latency_ms"],
"display": f"{cg_pinned['p50_latency_ms']} ms (p50, Exit {cg_pinned['exit_code']})",
"css_class": "is-fast",
},
{
"label": "pinned_omp_2_threads_p99",
"value": cg_pinned["p99_latency_ms"],
"display": (
f"{cg_pinned['p99_latency_ms']} ms "
f"(p99, thr={cg_pinned['throttle_ratio'] * 100:.1f}%)"
),
"css_class": "is-fast",
},
{
"label": "unpinned_16_threads_burst_p50",
"value": cg_burst_trap["p50_latency_ms"],
"display": f"{cg_burst_trap['p50_latency_ms']} ms (p50 + reclaim)",
"css_class": "is-mid",
},
{
"label": "unpinned_16_threads_burst_p99",
"value": cg_burst_trap["p99_latency_ms"],
"display": (
f"{cg_burst_trap['p99_latency_ms']} ms "
f"({p99_ratio}x stall, Exit {cg_burst_trap['exit_code']})"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_overlayfs_cow_footprint_mb",
"title": (
"OverlayFS 800 MB Weights: Inline --chown vs Separate RUN chmod + Late rm (MB)"
),
"metric_label": "Total OCI Image Size (MB)",
"items": [
{
"label": "inline_copy_chown_1W",
"value": ov_inline["total_oci_image_mb"],
"display": f"{ov_inline['total_oci_image_mb']:.0f} MB (0 MB wasted)",
"css_class": "is-fast",
},
{
"label": "separate_run_chmod_2W",
"value": ov_copyup["total_oci_image_mb"],
"display": (
f"{ov_copyup['total_oci_image_mb']:.0f} MB "
f"(+{ov_copyup['wasted_cow_and_deleted_mb']:.0f} MB copy-up)"
),
"css_class": "is-slow",
},
{
"label": "later_rm_whiteout_still_2W",
"value": ov_whiteout["total_oci_image_mb"],
"display": (
f"{ov_whiteout['total_oci_image_mb']:.0f} MB (.wh. hides file only!)"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_buildkit_uv_ci_build_s",
"title": (
f"CI Build Time Across {buildkit_bench['n_source_commits']} Commits: "
"COPY-Early pip vs BuildKit uv Split (s)"
),
"metric_label": "Total CI Build Time (seconds)",
"items": [
{
"label": "buildkit_uv_lockfile_split",
"value": buildkit_bench["buildkit_uv_split"]["total_ci_build_s"],
"display": (
f"{buildkit_bench['buildkit_uv_split']['total_ci_build_s']} s "
f"({buildkit_bench['buildkit_uv_split']['cache_hit_rate'] * 100:.1f}% "
"cache hit)"
),
"css_class": "is-fast",
},
{
"label": "legacy_copy_early_pip",
"value": buildkit_bench["legacy_copy_early"]["total_ci_build_s"],
"display": (
f"{buildkit_bench['legacy_copy_early']['total_ci_build_s']} s "
f"({buildkit_bench['legacy_copy_early']['cache_hit_rate'] * 100:.1f}% "
"cache hit)"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_dockerfile_and_registry_savings",
"title": "Harbor Content-Addressable Registry Storage & Hardened Dockerfile Audit",
"metric_label": "MB / Audit Score",
"items": [
{
"label": "oci_dedup_unique_blobs_mb",
"value": oci_dedup["unique_stored_mb"],
"display": (
f"{oci_dedup['unique_stored_mb']:.0f} MB unique "
f"(-{oci_dedup['dedup_savings_pct']}%)"
),
"css_class": "is-fast",
},
{
"label": "oci_naive_unshared_mb",
"value": oci_dedup["raw_cumulative_mb"],
"display": f"{oci_dedup['raw_cumulative_mb']:.0f} MB naive cumulative",
"css_class": "is-slow",
},
{
"label": "hardened_dockerfile_mb",
"value": df_hardened["projected_image_mb"],
"display": (
f"{df_hardened['projected_image_mb']} MB "
f"(Score {df_hardened['security_score']}/100)"
),
"css_class": "is-fast",
},
{
"label": "naive_dockerfile_mb",
"value": df_naive["projected_image_mb"],
"display": (
f"{df_naive['projected_image_mb']} MB "
f"(Score {df_naive['security_score']}/100)"
),
"css_class": "is-slow",
},
],
},
]
tables = [
{
"id": "table_runtime_isolation_comparison",
"title": (
"Container Runtime Comparison: Docker Rootful vs Rootless Podman vs Firecracker"
),
"columns": [
"runtime_mode",
"oci_or_vmm_engine",
"isolated_namespaces",
"host_uid_for_container_root",
"cold_start_ms",
"untrusted_ai_sandbox_safe",
],
"rows": [
[
rt["runtime_mode"],
rt["oci_runtime"],
f"{rt['isolated_namespace_count']}/7 (USER={ 'USER' in rt['namespaces_isolated'] })",
str(rt["container_uid0_mapped_to_host_uid"]),
f"{rt['cold_start_ms']} ms ({rt['control_overhead_mib']} MiB)",
str(rt["untrusted_ai_sandbox_safe"]),
]
for rt in (ns_docker, ns_podman, ns_firecracker)
],
},
{
"id": "table_cgroups_v2_and_signal_exit",
"title": "cgroups v2 CPU Quota, Memory Limits & PID 1 Signal Exit Matrix",
"columns": [
"scenario",
"threads_vs_quota",
"t_exhaust_vs_stall_ms",
"p99_latency_ms",
"exit_code",
"diagnosis",
],
"rows": [
[
"pinned_exec_tini",
f"{cg_pinned['parallel_threads']} thr / {cg_pinned['effective_vcpus']} vCPU",
f"{cg_pinned['t_exhaust_ms']} / {cg_pinned['t_stall_ms']} ms",
f"{cg_pinned['p99_latency_ms']} ms",
f"{cg_pinned['exit_code']} (SIGTERM)",
"Healthy low-jitter & graceful exit",
],
[
"unpinned_cfs_burst_shell_pid1",
f"{cg_burst_trap['parallel_threads']} thr / {cg_burst_trap['effective_vcpus']} vCPU",
f"{cg_burst_trap['t_exhaust_ms']} / {cg_burst_trap['t_stall_ms']} ms",
f"{cg_burst_trap['p99_latency_ms']} ms",
f"{cg_burst_trap['exit_code']} (SIGKILL)",
"CFS stall + /bin/sh swallowed SIGTERM",
],
[
"oom_memory_max_breach",
f"{cg_oom_kill['memory_current_mb']} / {cg_oom_kill['memory_max_mb']} MiB",
f"{cg_oom_kill['t_exhaust_ms']} / {cg_oom_kill['t_stall_ms']} ms",
f"{cg_oom_kill['p99_latency_ms']} ms",
f"{cg_oom_kill['exit_code']} (OOMKilled)",
"memory.max exceeded -> Kernel SIGKILL",
],
],
},
{
"id": "table_dockerfile_audit_comparison",
"title": "Real Lab Dockerfile Audit: Hardened Multi-Stage uv vs Dockerfile.naive",
"columns": [
"dockerfile",
"stages_and_pin",
"non_root_and_pid1",
"secret_leaks",
"projected_mb",
"score_and_grade",
],
"rows": [
[
df_hardened["dockerfile"],
(
f"{df_hardened['stage_count']} stages, "
f"sha256={df_hardened['has_pinned_sha256_digest']}"
),
(
f"non_root={df_hardened['non_root_user']}, "
f"exec={df_hardened['exec_form_pid1']}"
),
str(len(df_hardened["secret_leaks_detected"])),
f"{df_hardened['projected_image_mb']} MB",
f"{df_hardened['security_score']}/100 ({df_hardened['grade']})",
],
[
df_naive["dockerfile"],
(
f"{df_naive['stage_count']} stage, "
f"latest={df_naive['uses_mutable_latest']}"
),
(
f"non_root={df_naive['non_root_user']}, "
f"exec={df_naive['exec_form_pid1']}"
),
str(len(df_naive["secret_leaks_detected"])),
f"{df_naive['projected_image_mb']} MB",
f"{df_naive['security_score']}/100 ({df_naive['grade']})",
],
],
},
{
"id": "table_compose_network_and_hardening",
"title": (
"Real docker-compose.yml Service Topology, Network Segmentation & Hardening Audit"
),
"columns": [
"service",
"networks",
"host_ports",
"egress_isolated",
"read_only_and_cap_drop",
"healthcheck",
],
"rows": [
[
svc,
", ".join(info["networks"]),
", ".join(info["exposed_host_ports"]) or "none",
str(info["egress_isolated_internal_only"]),
f"ro={info['read_only_rootfs']}, cap_ALL={info['drops_all_caps']}",
str(info["has_healthcheck"]),
]
for svc, info in compose_audit["services"].items()
],
},
]
return {
"config": {
"quick": quick,
"lab_root": LAB_ROOT.name,
"docker_daemon_required": False,
},
"namespace_isolation": {
"rootful_docker": ns_docker,
"rootless_podman": ns_podman,
"firecracker_microvm": ns_firecracker,
},
"cgroups_v2": {
"pinned_exec": cg_pinned,
"burst_trap_shell": cg_burst_trap,
"oom_kill": cg_oom_kill,
},
"overlayfs": {
"inline": ov_inline,
"separate_chmod_2w": ov_copyup,
"late_rm_whiteout": ov_whiteout,
},
"buildkit_cache": buildkit_bench,
"oci_registry_dedup": oci_dedup,
"dockerfile_audits": {
"hardened": df_hardened,
"naive": df_naive,
},
"compose_audit": compose_audit,
"asgi_smoke": asgi_smoke,
"workbench_panels": {
"kpis": kpis,
"bars": bars,
"tables": tables,
},
}
def main() -> None:
parser = argparse.ArgumentParser(description="Run Lab 05 Container Engineering Benchmarks")
parser.add_argument("--quick", action="store_true", help="Run reduced iteration sweep")
parser.add_argument(
"--output",
type=Path,
default=LAB_ROOT / "artifacts" / "t2_ch06_lab05_results.json",
help="Output JSON path",
)
args = parser.parse_args()
payload = run_all_container_benchmarks(quick=args.quick)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(payload, indent=2), encoding="utf-8")
df_h = payload["dockerfile_audits"]["hardened"]
df_n = payload["dockerfile_audits"]["naive"]
cg_ok = payload["cgroups_v2"]["pinned_exec"]
cg_bad = payload["cgroups_v2"]["burst_trap_shell"]
ov_inline_mb = payload["overlayfs"]["inline"]["total_oci_image_mb"]
ov_2w_mb = payload["overlayfs"]["separate_chmod_2w"]["total_oci_image_mb"]
bk_speedup = payload["buildkit_cache"]["ci_build_speedup_x"]
oci_pct = payload["oci_registry_dedup"]["dedup_savings_pct"]
boot_dag = " -> ".join(payload["compose_audit"]["boot_order"])
print(
f"[1] Dockerfile Audit: hardened={df_h['security_score']}/100 "
f"({df_h['projected_image_mb']} MB) vs "
f"naive={df_n['security_score']}/100 ({df_n['projected_image_mb']} MB)"
)
print(
f"[2] cgroups v2 CFS: pinned p99={cg_ok['p99_latency_ms']} ms "
f"(Exit {cg_ok['exit_code']}) vs "
f"burst trap p99={cg_bad['p99_latency_ms']} ms (Exit {cg_bad['exit_code']})"
)
print(f"[3] OverlayFS 2W: inline={ov_inline_mb} MB vs separate chmod={ov_2w_mb} MB")
print(f"[4] BuildKit uv Split: speedup={bk_speedup}x, OCI dedup savings={oci_pct}%")
print(f"[5] Compose Boot DAG: {boot_dag} | output={args.output}")
if __name__ == "__main__":
main()
"""16-test offline verification suite for FSDS-SOTA-2026 Track 2 Lab 05 (container_ops_lab)."""
from __future__ import annotations
import ast
import asyncio
import json
import os
import subprocess
import sys
from pathlib import Path
import httpx
import pytest
LAB_ROOT = Path(__file__).resolve().parents[1]
SRC_DIR = LAB_ROOT / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
from container_ops_lab.app import create_container_app # noqa: E402
from container_ops_lab.container_audit_and_compose import ( # noqa: E402
analyze_compose_stack,
audit_dockerfile,
)
from container_ops_lab.linux_isolation_sim import ( # noqa: E402
KERNEL_NAMESPACES,
evaluate_namespace_isolation,
simulate_buildkit_layer_cache,
simulate_cgroups_v2_throttling_and_oom,
simulate_oci_registry_deduplication,
simulate_overlayfs_cow_and_whiteouts,
)
# Security-only AST ban on unsafe deserialization modules; PyYAML/FastAPI/HTTPX/NumPy are allowed.
FORBIDDEN_RUNTIME_IMPORTS = frozenset(
{
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
)
def test_01_namespace_isolation_rootful_vs_rootless_podman_vs_firecracker() -> None:
assert KERNEL_NAMESPACES == ("PID", "NET", "MNT", "UTS", "IPC", "USER", "CGROUP")
docker = evaluate_namespace_isolation("rootful_docker")
podman = evaluate_namespace_isolation("rootless_podman")
fc = evaluate_namespace_isolation("firecracker_microvm")
assert docker["daemon_required"] is True
assert docker["container_uid0_mapped_to_host_uid"] == 0
assert docker["docker_sock_host_root_risk"] is True
assert docker["untrusted_ai_sandbox_safe"] is False
assert podman["daemon_required"] is False
assert podman["oci_runtime"] == "crun"
assert podman["isolated_namespace_count"] == 7
assert podman["container_uid0_mapped_to_host_uid"] >= 100000
assert podman["subuid_range"] is not None
assert fc["hardware_vm_isolation"] is True
assert fc["untrusted_ai_sandbox_safe"] is True
assert fc["cold_start_ms"] <= 125.0
with pytest.raises(ValueError):
evaluate_namespace_isolation("unknown_engine")
def test_02_cgroups_v2_cfs_throttling_and_oom_exit_137_vs_143() -> None:
pinned = simulate_cgroups_v2_throttling_and_oom(
cpu_quota_us=100_000,
cpu_period_us=100_000,
active_threads=2,
memory_current_mb=320.0,
memory_high_mb=420.0,
memory_max_mb=512.0,
pid1_mode="exec_tini",
sigterm_sent=True,
)
burst = simulate_cgroups_v2_throttling_and_oom(
cpu_quota_us=100_000,
cpu_period_us=100_000,
active_threads=16,
memory_current_mb=470.0,
memory_high_mb=420.0,
memory_max_mb=512.0,
pid1_mode="shell_form",
sigterm_sent=True,
)
oom = simulate_cgroups_v2_throttling_and_oom(
memory_current_mb=512.0,
memory_high_mb=420.0,
memory_max_mb=512.0,
)
assert burst["t_exhaust_ms"] < pinned["t_exhaust_ms"]
assert burst["t_stall_ms"] > pinned["t_stall_ms"]
assert burst["p99_latency_ms"] > pinned["p99_latency_ms"] * 1.5
assert burst["reclaim_throttled"] is True
assert pinned["exit_code"] == 143
assert burst["exit_code"] == 137
assert oom["oom_killed"] is True
assert oom["exit_code"] == 137
def test_03_overlayfs_cow_2w_bloat_and_whiteouts() -> None:
inline = simulate_overlayfs_cow_and_whiteouts(
base_os_mb=120.0, weights_mb=800.0, separate_chmod_chown=False
)
copyup = simulate_overlayfs_cow_and_whiteouts(
base_os_mb=120.0, weights_mb=800.0, separate_chmod_chown=True
)
whiteout = simulate_overlayfs_cow_and_whiteouts(
base_os_mb=120.0,
weights_mb=800.0,
separate_chmod_chown=True,
delete_weights_in_later_run=True,
)
assert inline["total_oci_image_mb"] == 920.0
assert inline["amplification_factor_on_weights"] == 1.0
assert copyup["total_oci_image_mb"] == 1720.0
assert copyup["amplification_factor_on_weights"] == 2.0
assert copyup["wasted_cow_and_deleted_mb"] == 800.0
assert whiteout["visible_merged_rootfs_mb"] == 120.0
assert whiteout["total_oci_image_mb"] > 1720.0
assert "/models/.wh.model.safetensors" in whiteout["whiteout_markers"]
def test_04_buildkit_uv_split_layer_cache_efficiency() -> None:
res = simulate_buildkit_layer_cache(n_source_commits=10, deps_mb=420.0)
legacy = res["legacy_copy_early"]
uv_split = res["buildkit_uv_split"]
assert uv_split["cache_hit_rate"] > legacy["cache_hit_rate"]
assert uv_split["avg_rebuild_s"] < legacy["avg_rebuild_s"]
assert res["ci_build_speedup_x"] >= 4.0
assert res["network_bandwidth_saved_mb"] >= 3000.0
def test_05_oci_registry_sha256_blob_deduplication() -> None:
dedup = simulate_oci_registry_deduplication(
num_releases=6, base_os_mb=85.0, ml_runtime_mb=1150.0, app_layer_mb=8.5
)
assert dedup["unique_stored_mb"] < dedup["raw_cumulative_mb"]
assert dedup["dedup_savings_pct"] >= 75.0
assert dedup["head_dedup_skip_count"] == 10
assert dedup["actual_unique_blob_uploads"] == 8
def test_06_real_hardened_dockerfile_and_dockerignore_audit() -> None:
audit = audit_dockerfile(LAB_ROOT / "Dockerfile", LAB_ROOT / ".dockerignore")
assert audit["is_multistage"] is True
assert audit["stage_count"] == 2
assert audit["has_pinned_sha256_digest"] is True
assert audit["uses_mutable_latest"] is False
assert audit["secret_leaks_detected"] == []
assert audit["uses_buildkit_cache_mount"] is True
assert audit["copy_before_install_trap"] is False
assert audit["separate_chmod_copyup_trap"] is False
assert audit["non_root_user"] is True
assert audit["exec_form_pid1"] is True
assert audit["has_healthcheck"] is True
assert audit["has_stopsignal"] is True
assert audit["dockerignore_hardened"] is True
assert audit["security_score"] == 100
assert audit["grade"] == "HARDENED"
def test_07_real_naive_dockerfile_detects_all_anti_patterns() -> None:
audit = audit_dockerfile(LAB_ROOT / "Dockerfile.naive", None)
rule_ids = {f["rule_id"] for f in audit["findings"]}
assert audit["grade"] == "INSECURE"
assert audit["security_score"] <= 20
assert "DF001_SINGLE_STAGE" in rule_ids
assert "DF002_MUTABLE_LATEST_TAG" in rule_ids
assert "DF004_SECRET_IN_ARG_ENV" in rule_ids
assert "DF005_COPY_BEFORE_DEPS" in rule_ids
assert "DF007_OVERLAYFS_CHOWN_COPYUP" in rule_ids
assert "DF008_ROOT_USER" in rule_ids
assert "DF009_SHELL_FORM_PID1" in rule_ids
assert "DF010_MISSING_HEALTHCHECK" in rule_ids
def test_08_real_docker_compose_topological_boot_dag() -> None:
compose = analyze_compose_stack(LAB_ROOT / "docker-compose.yml")
assert compose["service_count"] == 3
boot = compose["boot_order"]
assert boot.index("postgres") < boot.index("api")
assert boot.index("redis") < boot.index("api")
assert compose["all_depends_use_service_healthy"] is True
assert "pgdata" in compose["named_volumes"]
def test_09_real_docker_compose_dual_network_internal_egress_isolation() -> None:
compose = analyze_compose_stack(LAB_ROOT / "docker-compose.yml")
assert compose["networks"]["frontend"]["internal"] is False
assert compose["networks"]["backend"]["internal"] is True
assert compose["data_services_egress_isolated"] is True
svcs = compose["services"]
assert svcs["postgres"]["egress_isolated_internal_only"] is True
assert svcs["postgres"]["exposed_host_ports"] == []
assert svcs["redis"]["egress_isolated_internal_only"] is True
assert svcs["redis"]["exposed_host_ports"] == []
assert set(svcs["api"]["networks"]) == {"frontend", "backend"}
def test_10_real_docker_compose_least_privilege_hardening() -> None:
compose = analyze_compose_stack(LAB_ROOT / "docker-compose.yml")
api_svc = compose["services"]["api"]
redis_svc = compose["services"]["redis"]
assert api_svc["read_only_rootfs"] is True
assert api_svc["has_tmpfs"] is True
assert api_svc["drops_all_caps"] is True
assert api_svc["no_new_privileges"] is True
assert api_svc["uses_init"] is True
assert api_svc["resource_limits"]["memory"] == "512M"
assert redis_svc["read_only_rootfs"] is True
assert redis_svc["drops_all_caps"] is True
assert redis_svc["no_new_privileges"] is True
def test_11_testcontainers_reference_syntax_and_contracts() -> None:
tc_path = LAB_ROOT / "testcontainers_reference" / "test_containers_e2e.py"
assert tc_path.is_file()
src = tc_path.read_text(encoding="utf-8")
ast.parse(src, filename=str(tc_path))
for marker in (
"PostgresContainer",
"RedisContainer",
"LogMessageWaitStrategy",
"HttpWaitStrategy",
"get_exposed_port",
"cap_drop",
"read_only=True",
):
assert marker in src, f"Missing {marker!r} in test_containers_e2e.py"
def test_12_fastapi_container_app_probes_and_degraded_drain() -> None:
app = create_container_app()
assert app.state.runtime.lifespan_started is False
async def _run_lifecycle_probes() -> None:
async with app.router.lifespan_context(app):
assert app.state.runtime.lifespan_started is True
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://container-lab",
) as client:
assert (await client.get("/health/live")).status_code == 200
assert (await client.get("/health/ready")).status_code == 200
app.state.runtime.degraded = True
assert (await client.get("/health/live")).status_code == 200
r_deg = await client.get("/health/ready")
assert r_deg.status_code == 503
assert r_deg.headers["content-type"].startswith("application/problem+json")
app.state.runtime.degraded = False
app.state.runtime.draining = True
assert (await client.get("/health/ready")).status_code == 503
asyncio.run(_run_lifecycle_probes())
assert app.state.runtime.lifespan_stopped is True
def test_13_fastapi_container_score_strict_pydantic_v2_and_stack_status() -> None:
app = create_container_app()
async def _exercise() -> tuple[httpx.Response, httpx.Response, httpx.Response]:
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://container-lab",
) as client:
ok = await client.post(
"/v1/container-score",
json={
"workload_name": "rag-embedder",
"cpu_quota_vcpus": 1.0,
"omp_threads": 2,
"rss_mb": 340.0,
"memory_max_mb": 512.0,
"weights_mb": 800.0,
"separate_chown": False,
},
)
bad = await client.post(
"/v1/container-score",
json={
"workload_name": "bad",
"cpu_quota_vcpus": "1.0",
"omp_threads": 2,
"rss_mb": 340.0,
"memory_max_mb": 512.0,
"weights_mb": 800.0,
"extra_rogue": 1,
},
)
stack = await client.get("/v1/stack-status")
return ok, bad, stack
ok_resp, bad_resp, stack_resp = asyncio.run(_exercise())
assert ok_resp.status_code == 200
ok_json = ok_resp.json()
assert ok_json["exit_code_predicted"] == 0
assert ok_json["wasted_cow_mb"] == 0.0
assert bad_resp.status_code == 422
assert bad_resp.headers["content-type"].startswith("application/problem+json")
stack_json = stack_resp.json()
assert stack_json["hardened_dockerfile"]["security_score"] == 100
assert stack_json["naive_dockerfile"]["grade"] == "INSECURE"
assert stack_json["compose_stack"]["data_services_egress_isolated"] is True
def test_14_cli_run_lab_demo_quick_exports_expected_schema(tmp_path: Path) -> None:
cli_env = os.environ.copy()
existing_pp = cli_env.get("PYTHONPATH", "")
cli_env["PYTHONPATH"] = f"{SRC_DIR}{os.pathsep}{existing_pp}" if existing_pp else str(SRC_DIR)
out_json = tmp_path / "t2_ch06_quick.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--quick",
"--output",
str(out_json),
],
cwd=str(LAB_ROOT),
env=cli_env,
capture_output=True,
text=True,
check=True,
)
assert "[1] Dockerfile Audit:" in proc.stdout
data = json.loads(out_json.read_text(encoding="utf-8"))
assert data["config"]["docker_daemon_required"] is False
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
def test_15_artifact_results_json_in_sync_and_valid() -> None:
art_path = LAB_ROOT / "artifacts" / "t2_ch06_lab05_results.json"
assert art_path.is_file()
data = json.loads(art_path.read_text(encoding="utf-8"))
assert data["dockerfile_audits"]["hardened"]["security_score"] == 100
assert data["dockerfile_audits"]["naive"]["security_score"] <= 20
assert data["compose_audit"]["data_services_egress_isolated"] is True
assert len(data["workbench_panels"]["kpis"]) == 6
def test_16_security_only_ast_scan_no_unsafe_deserialization() -> None:
py_files = [
*list((LAB_ROOT / "src").rglob("*.py")),
*list((LAB_ROOT / "scripts").rglob("*.py")),
*list((LAB_ROOT / "tests").rglob("*.py")),
*list((LAB_ROOT / "testcontainers_reference").rglob("*.py")),
]
assert len(py_files) >= 6
for py_file in py_files:
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
top = alias.name.split(".", 1)[0]
assert top not in FORBIDDEN_RUNTIME_IMPORTS, (
f"Forbidden import {top} in {py_file}"
)
elif isinstance(node, ast.ImportFrom) and node.module:
top = node.module.split(".", 1)[0]
assert top not in FORBIDDEN_RUNTIME_IMPORTS, (
f"Forbidden import {top} in {py_file}"
)
test_01), rootless_podman cô lập 7/7 namespaces (ánh xạ UID 0 container thành host UID 100000 qua /etc/subuid) nhưng vẫn chia sẻ ~300 syscalls nhân máy chủ; chỉ firecracker_microvm (hardware_vm_isolation=True, 118.0 ms, 4.5 MiB) mới đạt untrusted_ai_sandbox_safe=True.
cpu.max = 100000 100000 (1.0 vCPU), memory.high = 420 MiB, memory.max = 512 MiB trên máy chủ 16 lõi nhưng không ghim OMP_NUM_THREADS. Hiện tượng định lượng nào xảy ra trong Lab 05?test_02 và artifacts/t2_ch06_lab05_results.json: burst_trap_shell đốt cạn 100ms/16 = 6.25 ms, treo 93.75 ms (throttle_ratio = 24.53%), làm p99 tăng 10.94x. Hạn mức memory.high ép direct reclaim làm chậm phản hồi, còn memory.max giết OOM với Exit 137.
COPY model.safetensors /models/ (800 MB) rồi ở câu lệnh tiếp theo chạy RUN chmod 0644 /models/model.safetensors && chown 10001:10001 /models/model.safetensors, và sau đó lại chạy RUN rm -f /models/model.safetensors. Tổng dung lượng image OCI cuối cùng thay đổi ra sao?test_03 (simulate_overlayfs_cow_and_whiteouts): bất kỳ thay đổi nội dung hay inode metadata (chmod/chown) trên tệp thuộc lowerdir đều kích hoạt copy-up toàn tệp sang upperdir. Giải pháp là dùng COPY --chmod=0644 --chown=10001:10001 giữ kích thước ở 920 MB (1.0x).
Podman và lý do CMD uvicorn ... dạng shell-form gây lỗi mất gói khi dừng container?test_01, test_02 và test_07 xác minh: rootful_docker mang docker_sock_host_root_risk=True, còn rootless_podman dùng crun không daemon (34 ms khởi động, 2.8 MiB). shell_form khiến /bin/sh nuốt SIGTERM dẫn tới Exit 137, còn exec_tini trả Exit 143.
Dockerfile chuẩn Lab 05 so với Dockerfile.naive, kỹ thuật nào giúp giảm thời gian build trung bình qua 10 lần sửa mã nguồn từ 68.3 s xuống 3.64 s (18.76x nhanh hơn) và bảo vệ tuyệt đối bí mật khi build?test_04, test_06 và test_07: tách uv.lock khỏi COPY src/ tăng tốc 18.76x (683.0 s -> 36.4 s); còn nghiên cứu Stony Brook (ACM CCS) chỉ ra bí mật trong ARG/ENV/docker history bị bot khai thác chỉ sau 7.86 giây. Ngoài ra Alpine musl thiếu wheel manylinux (PEP 600) gây biên dịch từ mã nguồn cực chậm.
glibc) (hoặc slim-bookworm không root), tạo SBOM (SPDX 3.0/CycloneDX 1.6), quét Trivy, ký Cosign v3.0 và ghim @sha256: trên Harbor / GCP Artifact Registry thay vì :latest?docker sbom đã bị khai tử (thay bằng docker scout sbom / syft / trivy). Trong test_05 và test_06, Harbor khử trùng lặp blob tiết kiệm 82.76% (10/18 lớp bỏ qua qua HEAD), còn Dockerfile ghim @sha256: đạt 100/100 (HARDENED).
docker-compose.yml của Lab 05 (api, postgres, redis), tổ hợp thiết kế nào đảm bảo cả thứ tự khởi động không lỗi kết nối lẫn cách ly rò rỉ dữ liệu ra Internet?PyYAML ở test_08, test_09, test_10: boot_order = ['postgres', 'redis', 'api'], all_depends_use_service_healthy = True, data_services_egress_isolated = True (backend internal: true, 0 host ports), và api áp dụng đủ read_only, tmpfs, cap_drop: ALL.
pytest-xdist song song trên CI/CD để kiểm thử dịch vụ FastAPI kết nối PostgreSQL/Redis, vì sao Testcontainers (testcontainers_reference/test_containers_e2e.py) triệt tiêu lỗi chập chờn so với máy chủ DB thử nghiệm dùng chung hoặc cổng tĩnh 5432:5432?test_11 xác nhận testcontainers_reference/test_containers_e2e.py dùng PostgresContainer, RedisContainer, LogMessageWaitStrategy, HttpWaitStrategy và get_exposed_port cùng cơ chế Ryuk reaper (như mô hình 14M ca test/tháng tại Netflix).
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — 7 Namespaces, pivot_root & Mô hình Hóa Docker vs. Rootless Podman vs. Firecracker
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích ranh giới cô lập của 7 namespaces (PID, NET, MNT, UTS, IPC, USER, CGROUP), giải thích cơ chế chroot escape qua fd mở so với pivot_root + umount2(MNT_DETACH), và nêu lý do sandbox AI đa người thuê cần Firecracker (KVM).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi evaluate_namespace_isolation trong src/container_ops_lab/linux_isolation_sim.py cho cả 3 chế độ rootful_docker, rootless_podman, firecracker_microvm và chạy pytest -k test_01 -v.
Tiêu chí Đáp án & Số đối chứng
rootless_podman cô lập đủ 7/7 namespaces (ánh xạ UID 0 -> 100000 qua /etc/subuid, không cần daemon root, khởi động 34 ms với crun) nhưng vẫn chia sẻ ~300 syscalls; firecracker_microvm tách bằng KVM phần cứng (118 ms, 4.5 MiB) đạt untrusted_ai_sandbox_safe=True.
Bài tập 2 — Phân tích cgroups v2 CFS Throttling (p99), memory.high/max & Tín hiệu PID 1
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết phương trình \(t_{\text{exhaust}} = Q_{\text{cpu}} / N_{\text{thr}}\) cho cpu.max = 100000 100000 khi OMP_NUM_THREADS=16, giải thích tác động của memory.high (reclaim chậm) vs memory.max (OOM SIGKILL Exit 137), và lý do /bin/sh PID 1 biến SIGTERM thành Exit 137.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy simulate_cgroups_v2_throttling_and_oom trong linux_isolation_sim.py đối chiếu pinned (active_threads=2) với burst (active_threads=16, shell_form), kiểm chứng pytest -k test_02 -v.
Tiêu chí Đáp án & Số đối chứng
active_threads=16 đốt hết 100 ms trong 6.25 ms rồi treo 93.75 ms, đẩy p99 từ 16.1 ms lên 176.08 ms (10.94x); chạm memory.max hoặc shell_form trả Exit Code 137, còn exec_tini tắt êm với Exit Code 143.
Bài tập 3 — Chứng minh OverlayFS 2W Copy-on-Write, Whiteout .wh.*, BuildKit uv & OCI Deduplication
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh từng bước vì sao RUN chmod/chown ở lớp riêng sau COPY trọng số 800 MB nhân đôi thành 1,720 MB và vì sao RUN rm chỉ thêm .wh.*; đối chiếu với uv sync --locked --no-dev --no-install-project và khử trùng lặp sha256 trên Harbor.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Thực thi simulate_overlayfs_cow_and_whiteouts, simulate_buildkit_layer_cache, simulate_oci_registry_deduplication và chạy pytest -k "test_03 or test_04 or test_05" -v.
Tiêu chí Đáp án & Số đối chứng
Inline COPY --chown giữ ảnh ở 920 MB (1.0x) vs 1,720 MB (2.0x); tách lockfile uv tăng tốc rebuild trung bình 18.76x (68.3 s -> 3.64 s) tiết kiệm 3,780 MB; Harbor dedup sha256 giảm 82.76% dung lượng (7,461 -> 1,286 MB).
Bài tập 4 — Kiểm toán Thực tế Dockerfile Đa tầng Chuẩn Bảo mật vs. Dockerfile.naive
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Đối chiếu từng dòng Dockerfile và Dockerfile.naive cùng .dockerignore: phát hiện bí mật ARG/ENV, COPY . trước cài gói, thiếu @sha256:, người dùng root, CMD shell-form, thiếu HEALTHCHECK/STOPSIGNAL.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi audit_dockerfile trong container_audit_and_compose.py trên cả hai tệp của lab và chạy pytest -k "test_06 or test_07" -v.
Tiêu chí Đáp án & Số đối chứng
Dockerfile đạt 100/100 (HARDENED) (175.0 MB dự kiến, 2 stages, USER 10001:10001, exec-form CMD, @sha256:, .dockerignore sạch), còn Dockerfile.naive bị 0/100 (INSECURE) (1,255.0 MB) với 11 vi phạm bảo mật/lớp.
Bài tập 5 — Phân tích Đồ thị Docker Compose (service_healthy), Mạng internal: true & Testcontainers
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Giải thích thuật toán sắp xếp topo Kahn cho depends_on: condition: service_healthy, tác dụng chặn WAN egress của backend: { internal: true } trong docker-compose.yml, và cơ chế cổng ngẫu nhiên + Ryuk trong testcontainers_reference/test_containers_e2e.py.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy analyze_compose_stack(Path('docker-compose.yml')) và kiểm chứng pytest -k "test_08 or test_09 or test_10 or test_11" -v.
Tiêu chí Đáp án & Số đối chứng
boot_order = ['postgres', 'redis', 'api'], 100% cạnh dùng service_healthy, postgres và redis chỉ gắn backend (internal: true) với 0 host ports; api và redis bật read_only, tmpfs, cap_drop: ALL, no-new-privileges.
Bài tập 6 — Kiểm định Dịch vụ FastAPI Qua httpx.ASGITransport, Xuất CLI JSON & Cổng 16/16 pytest
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra /health/live, /health/ready (503 khi degraded hoặc draining), hợp đồng ContainerScoreRequest strict=True (422 application/problem+json), và đối chiếu toàn bộ 6 KPI, 4 biểu đồ thanh, 4 bảng trong JSON.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy ruff check src scripts tests testcontainers_reference, mypy src, python scripts/run_lab_demo.py --output artifacts/t2_ch06_lab05_results.json, và pytest -p no:cacheprovider -v.
Tiêu chí Đáp án & Số đối chứng
Tất cả ruff (All checks passed!), mypy --strict (0 issues), CLI run_lab_demo.py (6 KPI, 4 bars, 4 tables), và 16/16 pytest đều PASS 100% offline không cần Docker daemon và không dùng pickle/joblib.