Chương 01 — Nội tại GNU/Linux, Lập trình Shell Sản xuất, Makefile & Điều phối Tự động hóa
Từ ranh giới syscall/vDSO, VFS 4 tầng & sự cố log đã xóa 50 GiB (lsof +L1), mặt nạ bitmask POSIX/umask/ACL, bẫy Container PID 1, đại số chuyển hướng dup2(2) & Bash strict mode (flock -n) đến Makefile Work-Span DAG (.DELETE_ON_ERROR), systemd RandomizedDelaySec, cgroups v2 PSI & eBPF.
Unit ID:
T2-P1-U01
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 (R23&AIDE 1 R22): Bài 1 Fundamentals of Engineering — Linux (Introduction to GNU/Linux,Useful commands,Bash scripting,Compilation & Makefile,CronJob) kết hợp Lab thực hànhAIDE 1 R22(Install Ubuntu, Linux commands 101 & CLI-based website text crawler) trong 02-track-edai-raw-curriculum.md và đề cương nâng cấp 02-track-2-edai-sota-syllabus.md (Các nội dung Python nâng caouv/asynciochuyển giao sangch-02-production-python-engineering.md; container hóa chuyên sâu Docker/Podman/namespaces chuyển giao sangch-06-containers-docker-podman-and-compose.md)
Bài thực hành Song hành (Lab 01):labs/lab-01-linux-makefile-web-crawler/(linux_crawler_lab)
Tình huống Mở đầu: Bốn Thảm họa Vận hành Linux Đánh sập Hệ thống Dữ liệu & AI#
Mọi pipeline học máy, bộ thu thập dữ liệu web, hay máy chủ suy luận LLM cuối cùng đều chạy trên nhân GNU/Linux. Khi kỹ sư dữ liệu chỉ biết các lệnh bề mặt mà bỏ qua cơ chế nhân (VFS, fdtable, tín hiệu PID 1, dup2, Makefile DAG, cgroups v2), bốn sự cố kinh điển sau liên tục tái diễn ngoài môi trường sản xuất:
- Bóng ma Đĩa đầy
50.0 GiBSau Khi Xóa Log (df -h100%vs.du -sh0%): Một worker thu thập web vô tình bật log mứcINFOsuốt cuối tuần khiến/var/log/crawler/payloads.logphình lên50.0 GiBtrên phân vùng64 GiB. Kỹ sư trực chạyrm -f /var/log/crawler/payloads.log, nhưng chỉ 3 phút sau cả cụm sập với lỗiENOSPC: No space left on device. Công cụdf -hbáo đĩa đầy100%, trong khidu -shx /var/logchỉ thấy11.5 GiB(18%). Nguyên nhân gốc rễ: tiến trình daemon vẫn giữ bộ mô tả tệpfd=3mở trỏ tớiinodeđã bị hủy liên kết (i_nlink=0,open_fd_refs=1), khiến nhân Linux không thể giải phóng13,107,200khối đĩa4 KiB. - Bẫy
PID 1Trong Container — Treo30s, ChếtSIGKILL (137)& Rách Tệp JSONL: Khi Kubernetes nâng cấp deployment (kubectl rollout restart), kubelet gửiSIGTERM (15)cho container chạy dạng vỏ shell formCMD python worker.py(Docker tự bọc thành/bin/sh -c "python worker.py"mà/bin/shgiữPID 1và không chuyển tiếpSIGTERMcho tiến trình conpython), hoặc thậm chí dạng JSON exec formCMD ["python", "worker.py"]khi mã Python không đăng ký trình xử lýSIGTERMtường minh. Do nhân Linux đánh dấuPID 1bằng cờSIGNAL_UNKILLABLE(âm thầm bỏ qua các tín hiệu còn hành động mặc địnhSIG_DFL), container treo đúng30schờ hếtterminationGracePeriodSecondsrồi bị bắn hạ bằngSIGKILL (9)(Exit Code 137) — làm rách dở tệpcorpus.jsonlvà tích tụ tiến trình xác sốngZ(<defunct>). - Cơn Bão Chồng lấn
Cron& Đàn Trâu Dẫm Đạp (Thundering Herd)100Máy: Một cụm100máy thu thập web cài*/1 * * * *thường chạy xong trong5s. Khi trang đích chậm lên150s(\(\rho = T_{\text{exec}}/T_{\text{period}} = 2.5\)), không chỉ cả100máy đồng loạt nổ kết nối vào đúng giây:00mỗi phút, mà cron không có khóaflock(2)còn đẻ chồng3tiến trình trên mỗi máy — đẩy tổng kết nối đồng thời vọt lên300xtới4,000+và kích hoạtoom_kill, trong khi một cron job khác chết âm thầm vớiexit 127vìPATHmặc định của cron chỉ có/usr/bin:/bin. - Dữ liệu Đào tạo Nhiễm Độc từ
MakefileCắt cụt, Mấtstderrvì2>&1 > log, và Đổ vỡ ABIglibc/musl: Một quy tắcMakefilethiếu.DELETE_ON_ERROR:sập giữa chừng khi ghicorpus.jsonl, để lại tệp hỏng mangmtimemới khiến lần chạy saumakebáo'corpus.jsonl' is up to date. Kèm theo đó là lỗi đánh máy2>&1 > crawl.loglàm toàn bộ tracebackstderrbay mất raTTY, đóng gói Docker bằng Alpinemuslkhiến wheelmanylinuxlỗiGLIBCXXhoặc biên dịch25+phút, và gắn nhầmstrace -fvào dịch vụ2,000 RPSlàm độ trễp99nhảy vọt40x(12 ms -> 480 ms).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 01 và gói thực hành linux_crawler_lab, kỹ sư Dữ liệu & AI có đủ năng lực để:
- Giải phẫu Nhân GNU/Linux, VFS, Inode & Quyền POSIX từ Nguyên lý Gốc: Phân biệt không gian người dùng/nhân và chi phí
syscall/vDSO; chứng minh bất biến thu hồi khối đĩai_nlink == 0 AND open_fd_refs == 0; xử lý sự cố xóa log50.0 GiBkhông gián đoạn dịch vụ qualsof -nP +L1vàtruncatetrên/proc/<pid>/fd; tính chính xác quyền hiệu lựcbase_mode & (~umask & 0o777), bit đặc biệtSUID/SGID/Sticky (1777)vàmask::của POSIX ACL. - Làm chủ Vòng đời Tiến trình, Tín hiệu & Định tuyến I/O
dup2(2): Phân tíchfork()Copy-on-Write \(O(N_{\text{PTE}})\),execve()vàwaitpid(); phân biệt trạng tháiD(không thể ngắt ngay cả bằngSIGKILL),Z(chỉ dọn được qua tiến trình cha/PID 1) và bẫyPID 1container (tini+os.replace); và chứng minh đại số trái-sang-phải của> out.log 2>&1vs.2>&1 > out.logcùng ranh giới nguyên tửPIPE_BUF = 4096 B. - Viết Kịch bản Bash & Đồ thị
MakefileAn toàn Sản xuất: Vận dụng chế độ nghiêm ngặtset -Eeuo pipefail,IFS=$'\n\t', tránh bẫyif fn/SC2155(local x=$(...)) / mất biến qua subshell; cài khóa hạt nhânflock(2)(không bao giờ xóa tệp khóa) vàmktemp -d; nắm vững 4 giai đoạn biên dịch ELF (.i -> .s -> .o -> ELF),readelf -dvs.ldd,glibc manylinuxvs. Alpinemusl,LD_PRELOAD=libjemalloc.so.2; và xây dựngMakefileDAG có.PHONY,.DELETE_ON_ERROR:,mv $@.tmp $@với giới hạn song song Work–Span-j$(nproc). - Chuyển dịch Từ
CronJobSangsystemdTimers,cgroups v2,PSI&eBPFSOTA 2026: Chứng minh toán học bẫy hợp logicDOM OR DOWvà tích tụ chồng lấn củacron; triển khaisystemd.timer(RandomizedDelaySec,AccuracySec=1s,Persistent=true) chứng minh giảm đỉnh cụm theo Định luật Little \(\mathbb{E}[C] \approx N_{\text{nodes}}\bar{t}/J\); thiết lập cách lycgroups v2(MemoryHigh,MemoryMax,CPUQuota,KillMode=mixed), đọcjournaldJSON, giám sátPSI(some/full) chặn thrashing tiền-OOM, và thaystracebằngeBPF(fentry/CO-RE). - Xây dựng & Kiểm định Đầu–Cuối CLI Website Crawler Bất khả tri Mạng Ngoài (
linux_crawler_lab): Thiết kế CLI crawler chuẩn hóa RFC 3986, chặn rẽ nhánh SSRF/off-domain (cả qua chuyển hướng HTTP301/302/307/308và hậu giải phân giải DNS), chống trùng lặpSHA-256, ghi nguyên tử POSIXos.replace(), xử lý dừng duyên dángSIGTERM/SIGINT, kiểm tra sức khỏe--healthcheck, mã thoát tất định0/2/3, điều phối quaMakefile+crawl_pipeline.sh+systemd, và vượt qua trọn vẹn16/16ca kiểm thửpytest.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P1-U01, R23 & AIDE 1 R22)#
Nội dung Gốc (02-track-edai-raw-curriculum.md) |
Nâng cấp Chuẩn SOTA 2026 (ch-01) |
Mục trong Chương 01 | Tạo tác & Kiểm thử (linux_crawler_lab) |
|---|---|---|---|
1. Introduction to GNU/Linux & Useful commands (R23, AIDE 1 R22: Install Ubuntu, Linux commands 101) |
Cài đặt Ubuntu/WSL2 & Linux Commands 101 (apt, ls/find/grep, chmod/chown, ssh/scp), kiến trúc syscall/vDSO, FHS (/proc, /sys, /etc, /var/log, /run), VFS 4 lớp (super_block, inode, dentry, file), đếm tham chiếu i_nlink vs open_fd_refs, sự cố log 50 GiB (lsof -nP +L1), 12-bit POSIX (umask, SUID/SGID/Sticky), ACL mask::, fork CoW + execve, trạng thái R/S/D/Z/T, bẫy PID 1 (tini), chẩn đoán mạng/hệ thống (ss, ip -j, curl -fsSL, journalctl -o json), Ubuntu 24.04/26.04 LTS (PEP 668 + uv, AppArmor userns) |
Trụ cột 1 (§1.1–§1.3) + Trụ cột 2 (§2.0, §2.1, §2.4) + Trụ cột 3 (Cases 1, 2, 5) + Mermaid 1 + Widgets 1, 2 | posix_and_make_engine.py (resolve_posix_permissions, check_directory_access, VirtualFileSystem), Tests 1, 2, 3, 12 |
2. Bash scripting (R23, AIDE 1 R22) |
FD 0/1/2, đại số dup2(2) trái-sang-phải (> log 2>&1 vs 2>&1 > log), pipe 64 KiB & PIPE_BUF=4096, mkfifo, <(cmd), chế độ nghiêm ngặt set -Eeuo pipefail, IFS=$'\n\t', bẫy errexit/SC2155, khóa flock(2) vs .pid, mktemp -d / mktemp -p, jq/awk/sed/xargs -0 -P, ShellCheck, shfmt, bats-core |
Trụ cột 2 (§2.1–§2.2) + Trụ cột 3 (Case 4B) + Mermaid 2 + Widget 2 | scripts/crawl_pipeline.sh, simulate_fd_redirection, Tests 4, 10, 14 |
3. Compilation & Makefile (R23, AIDE 1 R22: Ubuntu, Makefile) |
Chuỗi 4 giai đoạn C (cpp -> cc1 -> as -> ld), .a vs .so, DT_SONAME/RPATH/RUNPATH, readelf -d vs ldd, bẫy manylinux/musl Alpine/GLIBCXX & jemalloc, Makefile DAG (\(G_{\text{DAG}}\)), mtime, $@/$</$^, .PHONY, .DELETE_ON_ERROR, mv $@.tmp $@, Work–Span -j$(nproc) (\(T_p \ge \max(T_1/p, T_\infty)\)), just / Ninja / Taskfile |
Trụ cột 2 (§2.3) + Trụ cột 3 (Cases 4A, 5) + Mermaid 3 + Widget 3 | Makefile, parse_makefile, plan_makefile_rebuild, Tests 5, 6, 10 |
4. CronJob & Điều phối SOTA (R23, AIDE 1 R22) |
Crontab 5 trường người dùng, bẫy DOM OR DOW & PATH, toán học chồng lấn \(N_{\text{active}}(t)\), systemd.timer (OnCalendar, RandomizedDelaySec, FixedRandomDelay=true, AccuracySec=1s, Persistent=true) + Định luật Little \(\mathbb{E}[C] \approx N\bar{t}/J\), cgroups v2 (MemoryHigh/MemoryMax/CPUQuota/KillMode=mixed + StateDirectory/LogsDirectory/RuntimeDirectory), journald, PSI (some/full) & eBPF (fentry/CO-RE) vs strace |
Trụ cột 2 (§2.4) + Trụ cột 3 (Cases 3, 5) + Mermaid 3 + Widget 3 | deploy/fsds-crawler.{service,timer}, deploy/crontab.example, parse_cron_expression, simulate_cron_vs_systemd_fleet, compute_psi_pressure, Tests 7, 8, 10 |
5. Lab: CLI Website Text Crawler (AIDE 1 R22) |
Máy chủ HTTP fixture cục bộ 127.0.0.1 (bất khả tri Internet), chuẩn hóa RFC 3986, SafeHTTPRedirectHandler + kiểm tra IP sau DNS chống SSRF mọi chặng redirect, HTMLParser trích văn bản, chống trùng SHA-256, ghi nguyên tử mkstemp + fsync + os.replace, SIGTERM + check_crawler_health, mã thoát 0/2/3, thực thi qua Makefile + Bash + Python + uv.lock |
Trụ cột 3 + Trụ cột 4 (§4.1–§4.3) | src/linux_crawler_lab/cli_crawler.py, scripts/run_lab_demo.py, artifacts/t2_ch01_workbench_results.json, Tests 9, 11, 13, 14, 15, 16 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 01 (Unified Notation)#
| Ký hiệu | Miền / Kiểu | Định nghĩa Chính xác Trong Chương 01 & linux_crawler_lab |
Quy ước Phân biệt |
|---|---|---|---|
| \(i_{\text{nlink}}, i_{\text{count}}, f_{\text{count}}\) | \(\mathbb{N}_{\ge 0}\) | Số mục thư mục trỏ tới inode; số tham chiếu inode trong RAM; số tham chiếu tới struct file |
Phân biệt với số tiến trình \(N_{\text{active}}\) |
| \(m_{\text{base}}, u_{\text{mask}}, m_{\text{eff}}\) | \(\text{0o000}..\text{0o7777}\) | Quyền gốc, mặt nạ tiến trình umask, quyền hiệu lực \(m_{\text{base}} \land (\neg u_{\text{mask}} \land \text{0o777})\) |
Viết bát phân dạng 0644 / 0o644 |
| \(\text{fd}_0, \text{fd}_1, \text{fd}_2, \text{PIPE\_BUF}\) | \(\mathbb{N}_{\ge 0}, 4096\text{ B}\) | Bộ mô tả stdin (0), stdout (1), stderr (2); ngưỡng ghi pipe nguyên tử POSIX trên Linux |
Phân biệt với open_fd_refs |
| \(G_{\text{DAG}} = (V, E)\) | Đồ thị có hướng | Đồ thị phụ thuộc Makefile: cạnh \((u, v)\) nghĩa là \(v\) phụ thuộc tiền đề \(u\) |
Chạy theo thứ tự topo Kahn |
| \(T_1, T_\infty, T_p, S(p)\) | \(\mathbb{R}_{>0}\) | Tổng công tuần tự, chiều dài đường găng, thời gian chạy song song -j(p), độ tăng tốc \(T_1 / T_p\) |
Phân biệt với \(T_{\text{period}}, T_{\text{exec}}\) của Cron |
| \(T_{\text{period}}, T_{\text{exec}}, \rho\) | \(\mathbb{R}_{>0}\) | Chu kỳ kích hoạt cron, thời lượng một lần chạy, hệ số sử dụng \(\rho = T_{\text{exec}} / T_{\text{period}}\) | — |
| \(N_{\text{nodes}}, J, \bar{t}, \mathbb{E}[C]\) | \(\mathbb{N}_+, \mathbb{R}_{\ge 0}\) | Số nút trong cụm, cửa sổ RandomizedDelaySec, thời lượng trung bình, đồng thời kỳ vọng \(N_{\text{nodes}}\bar{t}/J\) |
Phân biệt với \(N_{\text{active}}(t)\) trên 1 máy |
| \(\text{PSI}_{\text{some}}, \text{PSI}_{\text{full}}\) | \([0, 100]\%\) | Tỷ lệ cửa sổ \(W\) có \(\ge 1\) tác vụ nghẽn (some) vs. tất cả tác vụ không rỗi nghẽn (full) |
Đơn vị tích lũy total là \(\mu\text{s}\) |
| \(n_{\text{pages}}, P_{\text{coll}}\) | \(\mathbb{N}_{\ge 0}, [0, 1]\) | Số tài liệu thu thập; cận xác suất xung đột sinh nhật SHA-256 \(\approx n_{\text{pages}}^2 / 2^{257}\) |
— |
Trụ cột 1 — Nền tảng Hệ điều hành GNU/Linux: VFS, Inode, Quyền POSIX, Tiến trình & Đại số Tín hiệu#
1.1 Kiến trúc Nhân–Người dùng, ABI Gọi hệ thống, FHS & Bất biến Thu hồi Inode#
Ranh giới Đặc quyền & Chuyển ngữ cảnh syscall / vDSO#
Trên kiến trúc x86-64 (phân trang 48-bit), GNU/Linux tách biệt rạch ròi không gian người dùng (Userspace, Ring 3, 0x0000_0000_0000_0000–0x0000_7FFF_FFFF_FFFF, 128 TiB riêng mỗi tiến trình) và không gian nhân (Kernel space, Ring 0, 128 TiB ánh xạ chung với cờ trang chỉ dành cho Supervisor). Mọi thao tác chạm đĩa, mạng, đồng hồ hay bảng tiến trình đều bắt buộc vượt biên qua lời gọi hệ thống (syscall):
- Quy ước Thanh ghi (x86-64 Linux Syscall ABI): Số hiệu syscall đặt vào
RAX; tối đa 6 đối số truyền lần lượt quaRDI, RSI, RDX, R10, R8, R9(lưu ý: lệnh phần cứngsyscallghi đèRCXđể lưuRIPtrả về vàR11lưuRFLAGS, nên lớp bọcglibcchuyển đối số thứ 4 từRCXsangR10). - Chuyển chế độ & Trả về: Lệnh
syscallnâng cấp đặc quyền Ring \(3 \to 0\), nhảy quaentry_SYSCALL_64, chuyển sang ngăn xếp nhân, kiểm tra bảng phân phốisys_call_table[RAX](và chuyểnCR3nếu bật KPTI chống Meltdown). Giá trị trả về nằm trongRAX: đoạn[-4095, -1]biểu diễn mã lỗi-errnomàglibcđảo dấu vào biến cục bộ luồngerrnovà trả-1. - Độ trễ & Đường tắt
vDSO: Một syscall thường tốn khoảng50–300 ns. Các lời gọi đọc tần suất cực cao nhưclock_gettimehaygettimeofdayđược nhân ánh xạ trực tiếp trang bộ nhớ chỉ-đọc quavDSO(virtual Dynamic Shared Object, hiển thị trong/proc/<pid>/maps), thực thi trong5–15 nsmà không cần chuyển Ring \(3 \to 0\).
| Syscall Cốt lõi | Chức năng & Cờ Quan trọng | Bất biến Hệ thống & Bẫy Thực chiến |
|---|---|---|
openat(dirfd, path, flags, mode) |
Mở/tạo tệp tương đối theo dirfd (AT_FDCWD hoặc FD thư mục) |
Chống tấn công chuyển tráo symlink (TOCTOU) dọc đường dẫn; luôn kẹp O_CLOEXEC để không rò FD qua execve. |
read(fd, buf, n) / write(fd, buf, n) |
Đọc/ghi tối đa n byte vào page cache nhân |
Đọc/ghi ngắn (0 < r < n) là bình thường trên pipe/socket; cần lặp lại và xử lý EINTR/EAGAIN. write chưa đảm bảo xuống đĩa nếu thiếu fsync(2). |
close(fd) |
Gỡ fd khỏi fdtable và giảm f_count |
Luật sinh tử: Trên Linux, fd đã được giải phóng ngay cả khi close() báo -1 (EIO/ENOSPC). Không bao giờ lặp lại close(fd) trong code đa luồng; phải gọi fsync(fd) trước close(fd). |
statx(dirfd, path, flags, mask, buf) |
Đọc metadata inode (64-bit, an toàn Y2038) | Trả stx_btime, kích thước, quyền và stx_mnt_id thay thế stat/lstat cũ. |
unlinkat(dirfd, path, flags) |
Xóa mục thư mục (dentry) & giảm i_nlink đi 1 |
Không giải phóng dữ liệu đĩa nếu tiến trình khác vẫn đang mở fd hoặc mmap tới inode đó. |
fork() / clone3() / execve() / waitpid() |
Nhân bản tiến trình CoW, nạp ảnh ELF mới, thu hồi tiến trình con | execve giữ nguyên PID, cwd, các FD không gắn FD_CLOEXEC; waitpid thu gom xác Z và đọc wstatus. |
kill(pid, sig) / flock(fd, op) |
Gửi tín hiệu POSIX; khóa khuyến nghị gắn vào struct file |
flock(2) tự động nhả bởi nhân khi FD cuối cùng đóng (kể cả lúc chết do SIGKILL), ưu việt hơn tệp .pid. |
Bố cục Chuẩn Hệ thống Tệp FHS (/proc, /sys, /etc, /var/log, /run)#
/proc(procfs): Hệ thống tệp ảo trong RAM phơi bày trạng thái từng PID:/proc/<pid>/fd/(symlink tới tệp mở),/proc/<pid>/fdinfo/<n>(pos, cờ bát phânflagskiểm traO_APPEND),/proc/<pid>/status(VmRSS, mặt nạSigCgt/SigIgn),/proc/pressure/*(PSI)./sys(sysfs): Hệ phân cấp thiết bị & tham số nhân (/sys/fs/cgroup/chocgroups v2)./etc: Cấu hình tĩnh theo máy (/etc/crontab,/etc/ld.so.cache,/etc/systemd/system/). Tuyệt đối không đặt tệp khóa hoặc log biến đổi vào đây./var/log: Nhật ký bền vững qua khởi động lại (logrotatebắt buộc)./run(tmpfs): Trạng thái nhất thời trong RAM được dọn sạch mỗi lần boot — nơi chuẩn cho socket Unix, tệp.pidvà khóa/run/lock/*.lock.
Hệ thống Tệp Ảo (VFS) 4 Tầng & Định lý Thu hồi Inode#
Nhân Linux trừu tượng hóa mọi hệ tệp (ext4, xfs, tmpfs, overlayfs) qua 4 cấu trúc dữ liệu:
struct super_block: Đại diện một phân vùng đã gắn (s_blocksize, danh sách inode bẩn).struct inode: Đại diện một đối tượng tệp duy nhất quai_ino, lưu quyềni_mode,i_uid/i_gid,i_size, bộ đếm liên kết cứngi_nlink, bộ đếm tham chiếu trong bộ nhới_count, và con trỏ khối dữ liệu. Inode không hề chứa tên tệp.struct dentry: Mục thư mục ánh xạ cặp(parent_dentry, filename) -> inode, lưu đệm trong dcache tốc độ \(O(1)\).struct file(Open File Description): Đại diện một phiên mở tệp trong bảng tệp mở toàn hệ thống, chứaf_inode, con trỏ vị trí byte hiện tạif_pos, cờf_flags(O_APPEND,O_RDONLY), và bộ đếmf_count.
Từ kiến trúc 3 tầng fdtable[fd] -> struct file -> struct inode suy ra Bất biến Thu hồi Khối đĩa VFS: trình điều khiển hệ tệp chỉ thu hồi toàn bộ extent đĩa và xóa inode khi và chỉ khi đồng thời thỏa mãn cả hai điều kiện:
Giải mã Sự cố Bóng ma 50.0 GiB Log Đã xóa: Khi /var/log/crawler/payloads.log đạt \(50\text{ GiB} = 53,687,091,200\text{ B}\) (\(13,107,200\) khối \(4\text{ KiB}\)) và bị xóa bằng rm, lệnh gọi unlinkat(2) xóa dentry và hạ i_nlink từ 1 về 0. Vì tiến trình crawler (ví dụ PID 18422) vẫn giữ fd=3 mở (open_fd_refs = 1), du -sh (duyệt cây thư mục qua getdents64) thấy 0.0 GiB, trong khi df -h (gọi statfs(2) đọc super_block) vẫn báo 50.0 GiB đang chiếm dụng! Tra cứu bằng sudo lsof -nP +L1 sẽ liệt kê ngay dòng (deleted) cùng PID và số hiệu FD. Nếu cắt ngắn khẩn cấp bằng truncate -s 0 /proc/18422/fd/3:
- Khi tệp được mở với
O_APPEND(02000bát phân trong/proc/<pid>/fdinfo/3): mọiwrite(2)tự động nhảy về cuối tệp (0), giải phóng sạch50.0 GiBmà không tạo lỗ thưa. - Khi thiếu
O_APPEND:f_poscủastruct filevẫn kẹt ở50 GiB, nên lầnwrite()kế tiếp tạo ra một tệp thưa (sparse hole) có kích thước biểu kiến50 GiB+dù khối vật lý ít — bắt buộc phảiSIGUSR1hoặc reload tiến trình để mở lại FD mới.
Liên kết Cứng (Hard Link) vs. Liên kết Mềm (Symbolic Link)#
| Thuộc tính | Hard Link (ln src dst / linkat) |
Symbolic Link (ln -s target link / symlinkat) |
|---|---|---|
| Inode & Refcount | Dùng chung chính xác một i_ino (i_nlink tăng \(1 \to 2\)) |
Tạo inode mới loại S_IFLNK (0120000) chứa chuỗi đường dẫn đích |
| Xuyên Hệ tệp | Cấm (EXDEV) vì i_ino chỉ có nghĩa trong 1 super_block |
Cho phép xuyên phân vùng, mount point và đích chưa tồn tại |
| Thư mục | Cấm (EPERM) để bảo toàn cấu trúc cây DAG chống vòng lặp |
Cho phép (phát hiện vòng lặp qua giới hạn ELOOP = 40 bước) |
| Xóa tệp gốc | Dữ liệu vẫn nguyên vẹn chừng nào i_nlink >= 1 |
Trở thành dangling symlink; openat báo ENOENT |
1.2 Đại số Mặt nạ Bit POSIX, Bit Đặc biệt (1777/2775/4755) & POSIX ACL#
Mỗi inode lưu trường 16-bit st_mode, trong đó 4 bit cao (15..12) định danh loại tệp (S_IFMT) và 12 bit thấp (11..0, tức 0o7777) quy định quyền truy cập:
- 3 bit đặc biệt (
11..9):SUID (04000),SGID (02000),Sticky (01000). - 9 bit
rwx(8..0): chia làm 3 bộ ba cho Chủ sở hữu (u:0700), Nhóm (g:0070), và Người khác (o:0007). - Quy tắc hiển thị
ls -l: Bit đặc biệt phủ lên vị tríxcủa từng nhóm (s/Schouvàg;t/Tchoo), viết thường (s/t) nếu bitxnền bật (1), và viết HOA (S/T) nếu bitxnền tắt (0, vd.04644\(\to\)-rwSr--r--).
Phép toán Bitwise umask#
Khi tiến trình gọi openat(..., O_CREAT, m_base) hoặc mkdir(..., m_base), nhân Linux áp dụng mặt nạ tiến trình \(u_{\text{mask}} \in [0, \text{0o777}]\) theo công thức:
umask chỉ có khả năng tước bớt bit quyền chứ không bao giờ cấp thêm quyền:
- Tệp thông thường (\(m_{\text{base}} = \text{0o666}\)) dưới \(u_{\text{mask}} = \text{0o022}\) (
111 101 101sau phủ định):0o666 & 0o755 = 0o644(-rw-r--r--). - Thư mục cô lập dịch vụ (\(m_{\text{base}} = \text{0o777}\)) dưới \(u_{\text{mask}} = \text{0o027}\) (
111 101 000sau phủ định):0o777 & 0o750 = 0o750(drwxr-x---).
Tính Trực giao r/w/x trên Thư mục & Vai trò Sticky Bit (1777)#
Trên thư mục, quyền được xét lên bảng mục thư mục chứ không phải nội dung tệp con:
r(04): Chỉ cho phép liệt kê tên tệp (getdents64), không đủ để đọc metadata (statx) hay mở tệp nếu thiếux.x(01): Quyền đi xuyên (traverse) — chế độ0111(--x--x--x) cho phép đọc tệp/drop/secret.txtnếu biết trước tên chính xác, trong khi chặnls /drop(EACCES).w(02): Kết hợp vớix, cho phép tạo, đổi tên vàunlinkmọi tệp bên trong thư mục kể cả khi tệp đó có quyền0444chỉ-đọc và thuộc vềroot(vìunlinksửa khối dữ liệu của thư mục cha!).- Sticky Bit (
01000trên/tmp1777drwxrwxrwt): Bổ sung chốt chặn xóa ở tầng nhân (may_delete):
- POSIX ACLs (
getfacl/setfacl): Khi có ACL mở rộng (dấu+cuối cột quyềnls -l), 3 bit nhóm truyền thống không còn hiển thịgroup::nữa mà phản ánhmask::. Quyền hiệu lực của mọi mục ACL mở rộng đều bị kẹp trần bởientry_bits & mask_bits.
1.3 Vòng đời Tiến trình (fork CoW + execve + waitpid), Trạng thái & Bẫy PID 1#
Cơ chế fork() Copy-on-Write (CoW) & Độ phức tạp \(O(N_{\text{PTE}})\)#
Thay vì sao chép háo hức toàn bộ 4 GiB RAM vật lý (1,048,576 trang 4 KiB) chỉ để tiến trình con ném bỏ ngay khi gọi execve(), fork(2) nhân bản cấu trúc mm_struct và bảng trang ảo với độ phức tạp \(O(N_{\text{PTE}})\) (8 MiB mục bảng trang cho heap 4 GiB), xóa cờ ghi PTE_WRITE ở cả cha và con. Chỉ khi một bên thực hiện lệnh ghi mới xảy ra lỗi trang #PF (do_wp_page()), lúc đó nhân mới cấp phát và sao chép đúng một trang 4 KiB duy nhất vừa bị chạm. Khi tiến trình quá lớn (như Redis 64 GiB với 128 MiB bảng trang), nên dùng posix_spawn() (CLONE_VM | CLONE_VFORK) để tránh sao chép bảng trang khi gọi lệnh ngoài.
Năm Trạng thái Tiến trình & Bảng Tín hiệu Trọng yếu#
Mã ps |
Trạng thái Nhân | Cơ chế & Phản ứng Trước Tín hiệu |
|---|---|---|
R |
TASK_RUNNING |
Đang chạy trên lõi CPU hoặc nằm trong hàng đợi EEVDF/CFS chờ lát thời gian. |
S |
TASK_INTERRUPTIBLE |
Ngủ trên hàng đợi chờ I/O/timer (epoll_wait, pipe read); tỉnh dậy ngay khi nhận tín hiệu. |
D |
TASK_UNINTERRUPTIBLE |
Đang chờ I/O nhân cấp thấp (đĩa NVMe kẹt, NFS hard-mount). kill -9 (SIGKILL) KHÔNG GIẾT ĐƯỢC ngay lập tức vì tín hiệu chỉ kiểm tra khi thoát về Userspace để tránh hỏng DMA/journal nhân; tiến trình chỉ chết ngay khoảnh khắc I/O hoàn tất hoặc timeout. |
Z |
EXIT_ZOMBIE |
Tiến trình đã chết (đã giải phóng RAM và đóng toàn bộ FD), chỉ còn một ô PID + mã thoát chờ cha gọi waitpid(). kill -9 hoàn toàn vô tác dụng; phải sửa cha thu gom SIGCHLD hoặc kết thúc cha để PID 1 nhận nuôi và dọn dẹp. |
T / t |
STOPPED / TRACED |
Tạm dừng bởi SIGSTOP/Ctrl+Z hoặc đang bị ptrace (strace/gdb) giữ lại. |
Các tín hiệu POSIX chuẩn mà kỹ sư vận hành phải thuộc lòng: SIGHUP (1) (nạp lại cấu hình/mở lại log), SIGINT (2) (Ctrl+C), SIGPIPE (13) (ghi vào pipe đã mất độc giả \(\implies\) thoát 141), SIGTERM (15) (yêu cầu dừng duyên dáng — bắt giữ để xả tải và fsync, thoát 0), và SIGKILL (9) (không thể bắt/chặn trên tiến trình thường — nhân diệt tức khắc, mã thoát 128 + 9 = 137).
Bẫy PID 1 Trong Container (SIGNAL_UNKILLABLE & Zombie Accumulation)#
Bên trong mỗi PID namespace (container Docker/Kubernetes), nhân Linux đánh dấu tiến trình PID 1 bằng cờ SIGNAL_UNKILLABLE:
- Khác biệt Shell Form vs. JSON Exec Form & Cạm bẫy Bỏ qua
SIGTERM:- Với dạng vỏ (shell form)
CMD python worker.py, Docker tự bọc thành/bin/sh -c "python worker.py"— tiến trình/bin/shtrở thànhPID 1và không chuyển tiếpSIGTERMxuốngpython. - Với dạng JSON exec form
CMD ["python", "worker.py"],pythonchạy trực tiếp ởPID 1để nhận tín hiệu, nhưng khác vớiSIGINT(có sẵnKeyboardInterrupt), Python không cài trình xử lý mặc định choSIGTERM(vẫn giữSIG_DFL) — vì vậy nhân Linux trênPID 1âm thầm bỏ quaSIGTERMcho tới khi hết hạn30svàSIGKILLtừ namespace cha bắn chết tiến trình (Exit 137)!
- Với dạng vỏ (shell form)
- Tích tụ Xác sống
Z: Mọi tiến trình cháu bị mồ côi trong container được chuyển giao choPID 1của container đó. NếuPID 1không chạy vòng lặpwaitpid(-1, &status, WNOHANG), các tiến trình<defunct>lấp đầy bảng PID (pids.max) cho đến khifork()lỗiEAGAIN. - Cách khắc phục Chuẩn Sản xuất: Luôn bọc container bằng tiến trình init tối giản
/usr/bin/tini --(hoặcdocker run --init) kèm lệnh chính ở dạng exec form (ENTRYPOINT ["/usr/bin/tini", "--"]+CMD ["python", "worker.py"]), kết hợp đăng kýsignal.signal(signal.SIGTERM, ...)trong Python và ghi tệp quaos.replace()để kể cả khi bịSIGKILLđột ngột, dữ liệu trên đĩa vẫn toàn vẹn tuyệt đối.
Trụ cột 2 — Kiến trúc Luồng I/O, Bash Sản xuất, Biên dịch 4 Giai đoạn, Makefile DAG & Điều phối systemd + cgroups v2 + eBPF SOTA#
2.0 Cài đặt Ubuntu / WSL2 & Lệnh Linux Nhập môn (Linux Commands 101)#
Đối với kỹ sư Data/AI khởi đầu từ Windows/macOS hoặc quản trị máy chủ Ubuntu mới, nền tảng bắt buộc trước khi viết kịch bản Bash hay cấu hình systemd là dựng môi trường Linux chuẩn và làm chủ bốn nhóm thao tác nhập môn:
-
Cài đặt Ubuntu trên WSL2 (Windows) & Quản lý gói
apt: Mở PowerShell với quyền Administrator chạywsl --install -d Ubuntu-24.04(hoặc cài Ubuntu 24.04 LTS trên VM/Cloud). Sau khi vào shell Ubuntu, luôn làm mới chỉ mục gói trước khi cài công cụ phát triển:bash1 dòngsudo apt update && sudo apt install -y build-essential git curl jq shellcheck openssh-client -
Điều hướng, Lọc & Đọc Nhật ký Hệ thống (
pwd,ls,cd,find,grep): Xác định thư mục hiện hành (pwd), liệt kê cả tệp ẩn và quyền (ls -la), chuyển thư mục (cd /opt/fsds), tìm tệp log/cấu hình theo tên hoặc thời gian (find /var/log -type f -name "*.log" -mtime -1), tìm mẫu lỗi xuyên cây mã nguồn (grep -rn "ERROR" logs/hoặcrg -n), và đọc nhanh đầu/cuối tệp (head -n 20,tail -f). - Sửa Quyền & Sở hữu Tệp (
chmod,chown): Cấp quyền thực thi cho kịch bản (chmod u+x scripts/crawl_pipeline.sh), khóa chặt tệp cấu hình dịch vụ (chmod 0750 /var/lib/fsds-crawler), và chuyển quyền sở hữu thư mục dữ liệu cho user dịch vụ (sudo chown -R fsds:fsds /var/lib/fsds-crawler). -
Kết nối & Chuyển Tệp An toàn Qua Khóa SSH (
ssh/scpKey-Based Auth): Tạo cặp khóa Ed25519 hiện đại, chép khóa công khai lên máy chủ (không dùng mật khẩu trên môi trường sản xuất), đăng nhập và truyền tạo tác:bash4 dòngssh-keygen -t ed25519 -C "engineer@fsds-lab" ssh-copy-id -i ~/.ssh/id_ed25519.pub ubuntu@203.0.113.10 ssh -i ~/.ssh/id_ed25519 ubuntu@203.0.113.10 scp -i ~/.ssh/id_ed25519 data/corpus.jsonl ubuntu@203.0.113.10:/var/lib/fsds-crawler/
2.1 Bộ mô tả Tệp 0/1/2, Đại số dup2(2), Pipe 64 KiB & Công cụ Chẩn đoán SOTA#
Mỗi tiến trình khởi đầu với 3 bộ mô tả chuẩn: 0 (stdin), 1 (stdout), 2 (stderr). Khi vỏ POSIX (sh/bash) thực thi một dòng lệnh:
- Mọi đường ống (
|) được nối vàofd[1]trước tiên. - Các phép chuyển hướng (
>,2>&1,2>) được đánh giá từ trái sang phải bằng lời gọi hệ thốngdup2(oldfd, newfd)— sao chép con trỏ tớistruct filehiện tại chứ không tạo liên kết tượng trưng động!
| Lệnh Vỏ | Trình tự dup2(2) Trái \(\to\) Phải |
fd[1] (stdout) |
fd[2] (stderr) |
Chẩn đoán Hệ thống |
|---|---|---|---|---|
cmd > out.log 2>&1 |
(1) Mở out.log \(\to\) fd[1]; (2) dup2(1, 2) |
out.log |
out.log |
AN TOÀN: Dùng chung 1 struct file & f_pos, không ghi đè. |
cmd 2>&1 > out.log |
(1) dup2(1, 2) khi fd[1] còn trỏ TTY; (2) Mở out.log \(\to\) fd[1] |
out.log |
TTY |
LỖI RÒ RỈ: Toàn bộ lỗi stderr văng mất khỏi out.log! |
cmd > out.log 2> out.log |
(1) Mở out.log (desc #1) \(\to\) fd[1]; (2) Mở out.log (desc #2) \(\to\) fd[2] |
out.log (#1) |
out.log (#2) |
GHI ĐÈ CHÉO: 2 f_pos=0 độc lập dẫm lên dữ liệu của nhau. |
cmd 2>&1 >/dev/null | grep ERR |
(0) pipe \(\to\) fd[1]; (1) dup2(1, 2) \(\to\) pipe; (2) /dev/null \(\to\) fd[1] |
/dev/null |
pipe_write |
MẸO LỌC: Chỉ đẩy riêng stderr vào bộ lọc grep. |
- Pipe Vô danh (
pipe(2)),PIPE_BUF = 4096 B& Named FIFO (mkfifo): Pipe vô danh dùng bộ đệm vòng64 KiB(16 x 4 KiB) thuần trong RAM nhân (có thể mở rộng tới/proc/sys/fs/pipe-max-size). Chuẩn POSIX bảo đảm mọi thao tácwrite\(\le 4096\text{ B}\) (PIPE_BUFtrên Linux) lên pipe đều nguyên tử không bị xen kẽ giữa nhiều tiến trình ghi; nếu đầu đọc đóng hết, lệnh ghi nhậnSIGPIPE (141)/EPIPE.mkfifođặt tên cho cùng bộ đệm vòng đó trên cây thư mục (chặn đồng bộ cho tới khi có cả hai đầu đọc và ghi), còn phép thay thế tiến trình<(cmd)của Bash tạo pipe vô danh và truyền đường dẫn/dev/fd/N(lưu ý không hỗ trợlseek()). - Công cụ Chẩn đoán Mạng & Hệ thống Hiện đại (Thay thế Lệnh Cũ):
ss -tulpen/ss -tan state time-wait(iproute2truy vấn NetlinkSOCK_DIAGtốc độ \(O(1)\) thay thếnetstatchậm chạp quét/proc/net/tcp).ip -j addr/ip route get <ip>xuất JSON chuẩn hóa thay thếifconfig/route.curl -fsSL --retry 3 --retry-all-errors --max-time 30: Cờ-fépcurltrả mã lỗi khi gặp HTTP4xx/5xx(chặn thảm họa pipe trang lỗi HTML404/502vào trình thông dịchbashhay trình giải nén!).
2.2 Kỷ luật Lập trình Bash Sản xuất, Bẫy errexit, Khóa flock(2) & Phân tích Tĩnh ShellCheck#
Mọi kịch bản Bash vận hành đều phải mở đầu bằng khối bảo vệ nghiêm ngặt:
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit 2>/dev/null || true
IFS=$'\n\t'
| Cơ chế / Quy tắc | Giải thích Nguyên lý & Bẫy Sản xuất Phải Tránh |
|---|---|
set -Eeuo pipefail |
-e thoát ngay khi lệnh thất bại; -E kế thừa bẫy trap ... ERR vào bên trong hàm/subshell; -u báo lỗi biến chưa khởi tạo; -o pipefail (chính thức hóa trong POSIX.1-2024) lấy mã lỗi khác 0 ngoài cùng bên phải của đường ống. Cảnh báo errexit: đặt một hàm bên trong if my_fn; then hoặc my_fn || fallback sẽ tắt hoàn toàn set -e bên trong toàn bộ thân hàm my_fn! |
Lỗi SC2155 (local che mã lỗi) |
Viết local res=$(failing_cmd) luôn trả về mã 0 (từ chính lệnh nội tại local), vô hiệu hóa hoàn toàn set -e. Bắt buộc tách thành hai dòng: local res; res="$(failing_cmd)". |
| Ngoặc kép & Mất biến Subshell | Luôn bọc "$var" và "${arr[@]}" để chặn tách từ (SC2086) và bung ký tự đại diện (*, ?). Tránh cmd | while read ... vì vòng while chạy trong subshell và đánh mất mọi cập nhật biến; dùng < <(cmd) để giữ vòng lặp trong shell cha. |
Tạm an toàn mktemp -d & trap |
Không dùng /tmp/app.$$ (dễ dính lỗ hổng symlink TOCTOU). Dùng tmpdir="$(mktemp -d)" (O_CREAT|O_EXCL, 0700) kèm trap cleanup EXIT INT TERM (đọc $?, tháo trap - EXIT INT TERM rồi mới dọn để tránh lặp kép, và dùng dấu nháy đơn trong trap '...' tránh lỗi SC2064). |
Khóa hạt nhân flock(2) vs. .pid |
Khóa exec 9>"$LOCK_FILE"; flock -n 9 gắn với Open File Description trong nhân: nếu tiến trình chết đột ngột vì SIGKILL/OOM, nhân lập tức đóng FD và nhả khóa. Tuyệt đối không rm/unlink tệp khóa khi thoát, nếu không hai tiến trình chờ trên inode cũ đã unlink và inode mới tạo lại sẽ khóa song song! |
Xử lý Dòng (jq, awk, sed, xargs -0) |
Dùng jq cho JSON/JSONL, awk cho tổng hợp cột \(O(1)\) RAM, và find ... -print0 | xargs -0 -n 1 -P "$(nproc)" ... an toàn với tên tệp chứa khoảng trắng hoặc xuống dòng. Kiểm định CI tự động bằng ShellCheck, shfmt và bats-core. |
2.3 Chuỗi Biên dịch 4 Giai đoạn, ABI ELF .so, Makefile DAG & Work–Span Song song#
4 Giai đoạn Biên dịch C/Native & Hiện thực Liên kết Động Trong Python AI#
- Tiền xử lý (
cpp/gcc -E:.c -> .i): Bung#include, macro#define, lọc#ifdef. - Biên dịch (
cc1/gcc -S:.i -> .s): Phân tích AST \(\to\) SSA IR \(\to\) tối ưu hóa (-O2/-O3) \(\to\) hợp ngữ.s. - Hợp dịch (
as/gcc -c:.s -> .o): Tạo tệp đối tượng tái định vị ELF (ET_REL, chứa.text,.data,.bss, bảng ký hiệu.symtab). - Liên kết (
ld:.o+.a/.so\(\to\) ELF thực thi):- Thư viện tĩnh (
.a): Nhúng mã máy trực tiếp;ldquét từ trái sang phải nên thư viện phụ thuộc phải đặt sau tệp.o(gcc main.o -lm). - Thư viện động (
.so): Biên dịch với-fPIC, phân giải lúc nạp quaGOT/PLTbởild-linux-x86-64.so.2theo thứ tự:DT_RPATH(nếu thiếuDT_RUNPATH) \(\to\)LD_LIBRARY_PATH\(\to\)DT_RUNPATH\(\to\)/etc/ld.so.cache\(\to\)/lib,/usr/lib. NhãnDT_SONAME(vd.libssl.so.3) giữ hợp đồng ABI qua các bản vá nhỏ. - An toàn & ABI Python/AI: Tuyệt đối dùng
readelf -d <file>thay vìlddtrên tệp nhị phân không đáng tin cậy (tránh rủi rolddthực thi loader lạ). Trong hệ sinh thái Data/AI, chuẩnmanylinux(PEP 600) biên dịch sẵn trênglibc; tránh dựng ảnh bằng Alpinemusl(PEP 656) vì thiếu wheel AI khiếnpip/uvphải biên dịch từ mã nguồn suốt25+phút, dễ lỗiGLIBCXXkhi trộn với Conda, và dễ tràn ngăn xếp luồng mặc định128 KiBcủamusl(so với8 MiBcủaglibc). Khi dịch vụ Python/C++ đa luồng phình RSS giả tạo do phân mảnh arena củaglibc ptmalloc2(lên tới8 x số lõi), dùngMALLOC_ARENA_MAX=2hoặc nạpLD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2có thể cắt30–60%RSS đỉnh.
- Thư viện tĩnh (
Đồ thị Phụ thuộc Makefile DAG, .DELETE_ON_ERROR & Giới hạn Song song -j$(nproc)#
Một Makefile định nghĩa đồ thị có hướng không chu trình \(G_{\text{DAG}} = (V, E)\), trong đó mục tiêu không phải phony \(v\) chỉ được xây lại khi:
- Biến Tự động & Kỹ thuật An toàn:
$@(tên target hiện tại),$<(prerequisite đầu tiên),$^(toàn bộ prerequisite đã khử trùng),$*(phần khớp%trong mẫu quy tắc%.o: %.c), và:=(đánh giá tức thì 1 lần, an toàn hơn=đánh giá lười lặp lại$(shell ...)). - Hai Chốt An toàn Bắt buộc: (1) Khai báo
.PHONY:cho mục tiêu ảo (all,crawl,extract,test,clean) để không bị tê liệt nếu lỡ tạo tệp trùng tênclean; (2) Khai báo.DELETE_ON_ERROR:kết hợp ghi tạm nguyên tửmv -f $@.tmp $@và.SHELLFLAGS := -Eeuo pipefail -cđể nếu lệnh giữa chừng thất bại hoặc chết vìSIGKILL, tệp đầu ra hỏng không bao giờ nằm lại vớimtimemới đánh lừa lầnmaketiếp theo. - Định luật Work–Span cho
-j$(nproc): Với tổng công \(T_1 = \sum_{v} w(v)\) và đường găng nối tiếp dài nhất \(T_\infty\), thời gian chạy trên \(p\) luồng bị chặn dưới bởi bất đẳng thức Brent:
- Hệ sinh thái Xây dựng Hiện đại (
Makevs.justvs.Ninjavs.Taskfile): DùngMakefilekhi đồ thị phụ thuộc theo tệp (mtime) là cốt lõi; dùngjust(justfile) làm trình chạy lệnh tác vụ tiện dụng cho repo Python/AI (hỗ trợ.env, không bị bẫymtimegiả); đểNinjalàm backend tốc độ dưới mili-giây do CMake/Meson sinh ra khi biên dịch C++/CUDA extension; và dùngTaskfilekhi cần kiểm tra checksum nội dung đa nền tảng Windows/Linux.
2.4 CronJob vs. systemd Timers & Hạ tầng Linux 2026 (cgroups v2, PSI, eBPF)#
Cạm bẫy Toán học của CronJob 5 Trường#
Cấu trúc crontab (minute hour dom month dow) ẩn chứa 4 cạm bẫy sản xuất:
- Bẫy Hợp Logic Vixie (
DOM OR DOW): Nếu cả ngày-trong-tháng (DOM) và ngày-trong-tuần (DOW) cùng khác*, Vixie cron kích hoạt theo phép HỢP (OR) chứ không phải GIAO (AND)! Ví dụ0 9 13 * 5chạy ở mọi ngày 13 hàng tháng LẪN mọi Thứ Sáu (~61lần/năm thay vì chỉ Thứ Sáu ngày 13). - Môi trường Tối giản & Ký tự
%: Cron không đọc~/.bashrc(mặc địnhPATH=/usr/bin:/bin,SHELL=/bin/sh), gây lỗiexit 127vớiuv/.venv, và biến dấu%không thoát (date +%F) thành ký tự xuống dòng cấpstdin. - Bất thường Múi giờ DST: Giờ địa phương bị bỏ qua hoặc chạy đúp khi đổi giờ mùa hè — máy chủ sản xuất luôn chạy
UTC. - Độ trễ Chồng lấn & Bão Tích tụ: Khi \(T_{\text{exec}} > T_{\text{period}}\) (\(\rho > 1\)), số tiến trình đồng thời của cron không khóa tăng theo hàm bậc thang:
Kiến trúc systemd.timer + cgroups v2 & Toán học Phân tán Jitter#
Thay thế cron bằng cặp .timer + .service giải quyết đồng thời bốn vấn đề lớn:
- Kiểm soát Đàn Trâu (
RandomizedDelaySec=J+AccuracySec=1s+FixedRandomDelay=true): Rải đều \(N_{\text{nodes}}\) máy chủ trong cửa sổ \([0, J]\) thay vì cùng bắn tại:00. Lưu ý phải đặtAccuracySec=1sđể ghi đè mức gom mặc định1mincủa systemd vốn dĩ sẽ bó cụm lại các bộ đếm thời gian. Theo Định luật Little, mức đồng thời trung bình toàn cụm sập từ \(N_{\text{nodes}}\) xuống:
Với \(N_{\text{nodes}} = 100\) nút, \(\bar{t} = 5\text{ s}\), \(J = 45\text{ s}\), mức đồng thời kỳ vọng chỉ còn \(100 \times 5 / 45 = \mathbf{11.11}\) nút (-88.9% so với 100, và -96.0% từ 300 -> 12 khi so với kịch bản chồng lấn 3x). Kết hợp Persistent=true giúp tự động chạy bù 1 lần sau thời gian máy tắt.
- Cách ly Bán kính Nổ bằng
cgroups v2(/sys/fs/cgroup): ĐặtMemoryHigh=384M(kích hoạt thu hồi trang sớm để hãm phanh mềm) trước ngưỡng cứngMemoryMax=512M(giới hạnoom_killgói gọn trong riêng cgroup dịch vụ đó),CPUQuota=100%,TasksMax=64,DynamicUser=yes+ProtectSystem=strict+PrivateTmp=yes, kết hợpStateDirectory=fsds-crawler,LogsDirectory=fsds-crawler,RuntimeDirectory=fsds-crawler(để systemd cấp thư mục ghi được tại/var/lib/fsds-crawler,/var/log/fsds-crawler,/run/fsds-crawlerkhông bị lỗiEROFS/EACCES), vàKillMode=mixed(SIGTERMtới tiến trình chính trước khiSIGKILLdọn sạch cgroup sauTimeoutStopSec=30s). Kết hợpStandardOutput=journalđể truy vấn có cấu trúc không thể giả mạo (_PID,__CURSOR) quajournalctl -u fsds-crawler -o json.
Quan trắc Nhân Linux 2026: PSI, eBPF vs. strace & Nền tảng Ubuntu 24.04/26.04 LTS#
-
PSI(Pressure Stall Information,/proc/pressure/{cpu,memory,io}&<cgroup>/memory.pressure): Đo trực tiếp phần trăm thời gian thực mất do nghẽn tài nguyên thay cho chỉ sốload averagedễ đánh lừa, gồm hai chỉ số chính:some(\(\frac{100}{W}\int_0^W \mathbb{I}(\text{stalled} \ge 1)\,dt\)): ít nhất1tác vụ bị kẹt chờ tài nguyên.full: tất cả tác vụ không rỗi cùng bị kẹt đồng thời (dấu hiệu thrashing vùng nhớ nghiêm trọng trước khi chạm OOM;systemd-oomdlắng nghe trực tiếpmemory.pressuređể ngắt sớm cgroup gây nghẽn trước khi treo toàn máy!).eBPF(fentry/fexit,tracepoint,BPF_LSM,XDP,BTF/CO-RE) vs.strace:stracedùngptrace(2)dừng tiến trình đích 2 lần cho mỗi syscall, gây chậm10x–100x+(tử huyệt khi gắn vào dịch vụ sản xuất). Ngược lại,eBPFchạy bytecode được trình xác minh tĩnh trong nhân kiểm duyệt và biên dịch JIT, tổng hợp histogram ngay trongBPF_MAPvới chi phí chỉ vài nano-giây (< 1–3%CPU).- Chuẩn Ubuntu 24.04 LTS (Kernel 6.8) / 26.04 LTS (Kernel 7.0): Bắt buộc tuân thủ
PEP 668(EXTERNALLY-MANAGEDcấmpip installtoàn cục — luôn cô lập bằnguvhoặc.venv), hiểu cơ chếAppArmorhạn chếunprivileged usernschống leo thang đặc quyền, và bậtDelegate=yeschocgroups v2nếu chạy container không root (Podman/Docker).
Trụ cột 3 — Kỹ thuật Thực chiến: Phân tích 5 Sự cố Sản xuất, Mã Mẫu Chuẩn & Playbook Chọn Công cụ#
3.1 Tổng kết 5 Sự cố Công nghiệp & Mẫu Thiết kế Cứng hóa#
- Sự cố 1 — Đĩa
/var/logĐầy100%Saurm(50.0 GiBBóng ma Open-FD): Kiểm tradf -h /var/logvs.du -shx /var/log, truy vết bằngsudo lsof -nP +L1 /var/logvà xem cờ02000(O_APPEND) trong/proc/<pid>/fdinfo/<fd>. Giải phóng ngay không mất kết nối bằngsudo truncate -s 0 /proc/<pid>/fd/<fd>(nếu cóO_APPEND) hoặc gửiSIGUSR1mở lại tệp; về dài hạn bắt buộc cấu hìnhlogrotatekết hợpstdout/stderrcó giới hạn dung lượng. - Sự cố 2 — Container Treo
30s& Vỡ JSONL VìExit 137(PID 1Trap): Kiểm tra mặt nạ tín hiệugrep SigCgt /proc/1/status(bit 150x4000củaSIGTERM) và zombieps -eo pid,ppid,stat,comm | awk '$3 ~ /^Z/'. Sửa dứt điểm bằngENTRYPOINT ["/usr/bin/tini", "--"], đăng kýsignal.signal(signal.SIGTERM, ...)trong Python, và mọi phép ghi tệp phải tuân thủ mô hình tạo tạm cùng thư mục +fsync+os.replace(). - Sự cố 3 —
CronChồng lấn3x& Thundering Herd100Máy (exit 127): Luôn khai báo tường minhSHELL=/bin/bashvàPATH=..., bọc mọi tác vụ bằngflock -n, và nâng cấp lênsystemd.timer(RandomizedDelaySec=45s,AccuracySec=1s,Persistent=true) +cgroups v2để triệt tiêu đồng thời cả chồng lấn đơn máy lẫn đỉnh lưu lượng toàn cụm. - Sự cố 4 —
MakefileBáo "Up to Date" Trên Dữ liệu Hỏng & Lỗi2>&1 > log: Bắt buộc khai báo.DELETE_ON_ERROR:,.ONESHELL:,.SHELLFLAGS := -Eeuo pipefail -c, chỉ quảng bá tạo tác bằngmv -f $@.tmp $@sau khi kiểm tratest -s $@.tmp, và luôn đặt chuyển hướng theo đúng thứ tự> /var/log/job.log 2>&1. - Sự cố 5 — Sập
.soGLIBCXX/ Alpinemusl& Quá tảistrace(40x p99): Chọn ảnh nềnpython:3.12-slim(glibctương thíchmanylinux), chẩn đoán xung độtConda/pipbằngreadelf -dvàLD_DEBUG=libs, điều chỉnhLD_PRELOAD=libjemalloc.so.2nếu đa luồng phình RSS, và tuyệt đối dùngbpftrace/PSIthaystracetrên lưu lượng nóng.
3.2 Mẫu Mã Sản xuất Hợp chuẩn (Hardened Production Snippets)#
1) Kịch bản Bash Chuẩn Sản xuất (scripts/crawl_pipeline.sh)#
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit 2>/dev/null || true
IFS=$'\n\t'
tmpdir=""
stage_jsonl=""
OUT_JSONL="${OUTPUT_JSONL:-data/corpus.jsonl}"
LOCK_FILE="${LOCK_FILE:-/run/fsds-crawler/crawl.lock}"
cleanup() {
local rc=$?
trap - EXIT INT TERM
[[ -n "$stage_jsonl" && -f "$stage_jsonl" ]] && rm -f -- "$stage_jsonl"
[[ -n "$tmpdir" && -d "$tmpdir" ]] && rm -rf -- "$tmpdir"
exit "$rc"
}
trap cleanup EXIT INT TERM
out_dir="$(dirname -- "$OUT_JSONL")"
mkdir -p -- "$out_dir" "$(dirname -- "$LOCK_FILE")"
tmpdir="$(mktemp -d)"
stage_jsonl="$(mktemp -p "$out_dir" ".corpus.jsonl.XXXXXX")"
exec 9>"$LOCK_FILE"
flock -n 9 || { printf '[SKIP] previous run holds flock\n'; exit 0; }
# Đánh giá trái-sang-phải: fd[1] trỏ tới run.log trước, sau đó dup2(1, 2);
# staging cùng thư mục out_dir bảo đảm mv -f dùng atomic rename(2) không bao giờ dính EXDEV!
python3 -m linux_crawler_lab.cli_crawler --serve-fixtures --output-jsonl "$stage_jsonl" > "${tmpdir}/run.log" 2>&1
mv -f -- "$stage_jsonl" "$OUT_JSONL"
stage_jsonl=""
2) Ghi Nguyên tử POSIX & Khớp URL An toàn SSRF (Python 3.10+)#
import os
from pathlib import Path
import tempfile
from urllib.parse import urlsplit
def atomic_write_text(target_path: Path, content: str) -> None:
"""Ghi tạm trên CÙNG hệ tệp -> fsync -> os.replace (chống EXDEV và rách dữ liệu khi SIGKILL)."""
target_path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp_name = tempfile.mkstemp(prefix=f".{target_path.name}.", suffix=".tmp", dir=str(target_path.parent))
tmp_path = Path(tmp_name)
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh:
fh.write(content)
fh.flush()
os.fsync(fh.fileno())
os.replace(tmp_path, target_path)
except BaseException:
tmp_path.unlink(missing_ok=True)
raise
3.3 Playbook Chọn Công cụ & Bảng Tra cứu Nhanh 6 Chế độ Hỏng#
| Bài toán Kỹ thuật | Công cụ Khuyến nghị (2026) | Tránh Dùng Khi | Chốt Bảo vệ Bắt buộc |
|---|---|---|---|
Keo dán quy trình, đường ống CLI (< 100 dòng) |
Bash >= 4 + ShellCheck |
Phân tích HTML/JSON phức tạp, thử lại jitter, crawler | set -Eeuo pipefail, "$var", mktemp -d, flock -n |
| Web crawler, xử lý dữ liệu, chính sách bảo mật | Python 3.10+ (uv + Pydantic v2) |
Bật tắt dịch vụ hệ thống mức sơ khai | Khớp tên miền host == d || .d, SHA-256, os.replace(), mã 0/2/3 |
Đồ thị phụ thuộc tệp theo mtime |
GNU Makefile (-j$(nproc)) |
Chạy tác vụ không tạo tệp hoặc không theo thời gian | .DELETE_ON_ERROR:, .PHONY:, .SHELLFLAGS, mv $@.tmp $@ |
Trình chạy lệnh repo hiện đại (.env, tham số) |
just (justfile) |
Cần bỏ qua bước dựa trên mtime của tệp đầu ra |
set shell := ["bash", "-Eeuo", "pipefail", "-c"] |
| Lập lịch định kỳ trên máy chủ Linux | systemd.timer + .service (cgroups v2) |
Chạy trên container không có daemon systemd |
RandomizedDelaySec, AccuracySec=1s, Persistent=true, MemoryMax |
| Truy vết độ trễ trên lưu lượng nóng | eBPF (bpftrace) + cgroups v2 PSI |
Tìm lỗi thiếu tệp nhanh trong môi trường dev cục bộ | Tuyệt đối không gắn strace -f vào worker sản xuất |
| # | Chế độ Hỏng (Failure Mode) |
Triệu chứng Thực tế | Lệnh Chẩn đoán Chuẩn | Khắc phục Dứt điểm |
|---|---|---|---|---|
| 1 | Tệp Xóa Còn Mở FD (ENOSPC) |
df báo 100%, du chỉ thấy 18% |
sudo lsof -nP +L1 & cat /proc/<pid>/fdinfo/<fd> |
truncate -s 0 /proc/<pid>/fd/<fd> (nếu O_APPEND), SIGUSR1 + logrotate |
| 2 | Bẫy Container PID 1 (137) |
rollout treo 30s, chết SIGKILL, đầy Z |
grep SigCgt /proc/1/status & ps -eo stat,comm |
tini exec-form + handler SIGTERM + ghi os.replace() |
| 3 | Bão Cron & Thiếu PATH |
exit 127 hoặc nhân bản 3x tràn RAM |
ps auxf, systemctl list-timers, journalctl |
flock -n + PATH tường minh, chuyển systemd.timer có Jitter |
| 4 | Makefile Hỏng & 2>&1 > |
make báo up to date trên JSON lỗi; log mất stderr |
ls -l --full-time |
.DELETE_ON_ERROR:, mv $@.tmp $@, đặt > log 2>&1 đúng thứ tự |
| 5 | Đứt ABI .so / Alpine musl |
GLIBCXX_3.4.30 not found; build chậm 25m |
readelf -d, strings libstdc++.so.6, LD_DEBUG=libs |
Dùng python:3.12-slim (glibc), LD_PRELOAD=libjemalloc.so.2 |
| 6 | Nghẽn strace & Thrashing PSI |
Gắn debugger làm p99 vọt 40x; OOM bất ngờ |
cat /proc/pressure/memory (some/full) |
Dùng bpftrace + systemd-oomd theo ngưỡng memory.pressure |
Trụ cột 4 — Thực hành Lab 01 (linux_crawler_lab) & Kiểm định Hợp đồng 16 Ca pytest#
Bài thực hành đồng hành tại labs/lab-01-linux-makefile-web-crawler/ kết hợp đầy đủ các tệp vận hành Linux thật (Makefile, scripts/crawl_pipeline.sh, deploy/fsds-crawler.service, deploy/fsds-crawler.timer, deploy/crontab.example) với gói Python thuần chuẩn + Pydantic v2 (linux_crawler_lab) chạy hoàn toàn ngoại tuyến và tất định trên cả Linux lẫn Windows.
4.1 Kiến trúc Gói linux_crawler_lab & Nguyên tắc Bất khả tri Mạng Ngoài#
labs/lab-01-linux-makefile-web-crawler/
├── Makefile # Đồ thị DAG thực (.DELETE_ON_ERROR, .PHONY, -j2, mv $@.tmp $@)
├── pyproject.toml # PEP 621 (src/ layout, pydantic>=2.0, cấu hình [tool.ruff] / [tool.mypy])
├── uv.lock # Khóa phiên bản phụ thuộc tái lập cho uv sync --locked
├── README.md # Hướng dẫn 100% tiếng Việt
├── scripts/
│ ├── crawl_pipeline.sh # Bash strict mode (set -Eeuo pipefail, tách SC2155, trap, mktemp -p, flock -n)
│ └── run_lab_demo.py # CLI workbench xuất artifacts/t2_ch01_workbench_results.json (kèm cờ --quick)
├── deploy/
│ ├── fsds-crawler.service # systemd DynamicUser + StateDirectory/LogsDirectory/RuntimeDirectory + cgroups v2
│ ├── fsds-crawler.timer # OnCalendar + RandomizedDelaySec=45s + AccuracySec=1s + Persistent=true
│ └── crontab.example # User crontab 5 trường chuẩn (PATH, flock -n, > log 2>&1) + cảnh báo phản mẫu
├── src/
│ └── linux_crawler_lab/
│ ├── __init__.py
│ ├── posix_and_make_engine.py # POSIX bitmask, VFS inode leak, dup2, Makefile DAG, Cron/systemd/PSI
│ └── cli_crawler.py # LocalFixtureServer, SafeHTTPRedirectHandler + post-DNS SSRF guard, SIGTERM/healthcheck
├── tests/
│ └── test_linux_crawler_lab.py # 16 ca kiểm thử pytest + AST security scan cấm giải tuần tự không an toàn
└── artifacts/
└── t2_ch01_workbench_results.json
Hợp đồng An toàn Môi trường: Trình quét AST trong Test 14 bảo đảm 0 import giải tuần tự không an toàn (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal), SafeHTTPRedirectHandler + validate_target_url kiểm tra lại scheme, allowlist và IP hậu phân giải DNS trên mọi chặng redirect 301/302/307/308 để chặn SSRF (cho phép loopback chỉ khi bật rõ allow_loopback_test=True với máy chủ fixture 127.0.0.1:0 tự đóng trong finally).
4.2 Hướng dẫn Qua 2 Mô-đun Cốt lõi & 6 Chỉ số Workbench (artifacts/t2_ch01_workbench_results.json)#
posix_and_make_engine.py: Định nghĩa hợp đồngPydantic v2(PosixPermissionSpec,MakefileRuleSpec,CronScheduleSpec), hàm tính bitmaskresolve_posix_permissions&check_directory_access, lớp mô phỏngVirtualFileSystemtái hiện trọn vẹn vòng đời log50.0 GiB, hàm mô phỏng đánh giá trái-sang-phảisimulate_fd_redirection, trình phân tíchMakefilethựcparse_makefile+ lập lịch Work–Span & mô phỏng.DELETE_ON_ERRORplan_makefile_rebuild, trình phân tíchcronphát hiệndom_or_dow_quirk+ mô phỏng cụmsimulate_cron_vs_systemd_fleet, và hàm hợp nhất khoảng nghẽncompute_psi_pressure.cli_crawler.py: Cung cấpLocalFixtureServerphục vụ 8 trang HTML chuẩn + 1 trang/missing-404+ kiểm thử chuyển hướng 301/302/307/308,canonicalize_url(RFC 3986 + bỏutm_*),validate_target_url+SafeHTTPRedirectHandlerchặn SSRF hậu DNS (169.254.169.254, IP private/loopback/reserved),is_url_allowed,extract_html_text_and_links, chống trùngSHA-256, ghi nguyên tửatomic_write_text/atomic_write_jsonl, trình xử lýSIGTERM/SIGINT(install_signal_handlers/restore_signal_handlers), đầu dò sẵn sàngcheck_crawler_health(--healthcheck), và mã thoát0/2/3.
Chạy workbench CLI từ thư mục gốc của lab (nhãn biểu đồ DAG phản ánh rõ "Simulated Makefile Work-Span DAG Latency" của posix_and_make_engine.py):
python scripts/run_lab_demo.py --quick --output artifacts/t2_ch01_workbench_results.json
Bốn khối kết quả thực nghiệm (stdout & artifacts/t2_ch01_workbench_results.json với 6 KPI, 4 biểu đồ cột, 4 bảng chi tiết):
Chỉ số KPI (artifacts/t2_ch01_workbench_results.json) |
Giá trị Đo kiểm Thực tế (--quick) |
Trạng thái |
|---|---|---|
kpi_posix_umask_and_sticky (POSIX umask 0027 & Sticky Guard) |
0750 (drwxr-x---) (0666&~0022=0644 (-rw-r--r--); 1777 chặn người khác xóa=True) |
ok (Đã xác minh) |
kpi_vfs_deleted_log_leak (50 GiB Deleted Log df vs du) |
50.0 vs 0.0 GiB (i_nlink=0, open_fd=1, lsof +L1=1; cắt /proc/fd về 0.0 GiB) |
critical (Tái hiện rò rỉ) |
kpi_fd_dup2_redirection (FD 0/1/2 >log 2>&1 vs 2>&1 >log) |
out.log vs tty (2>&1 >out.log rò stderr ra TTY shared_desc=False; >out.log 2>&1 an toàn) |
warn (Cảnh báo thứ tự) |
kpi_makefile_dag_parallel (Makefile DAG -j2 vs -j1 & Incremental) |
7.0s (1.71x) (T_inf=7.0s, T1=12.0s; chạm posix_and_make_engine.py chạy lại 2/4 tệp 6.0s, bỏ qua 2/4; .DELETE_ON_ERROR sửa lỗi sập) |
ok (Đã xác minh) |
kpi_cron_vs_systemd_fleet (100-Node Fleet Peak Cron vs systemd Jitter) |
300 -> 12 (-96.0%) (chồng lấn đơn máy 3 vs flock=1 bỏ qua 4 tick; Little's Law E[C]=11.11; PSI thrashing 18.4%/12.5%) |
ok (Đã xác minh) |
kpi_offline_cli_crawler (Offline CLI Crawler) |
9 -> 7 docs (blk=2) (SHA-256 loại 1 trùng /docs/mirror, URL dedup 1, HTTP 404=1, JSONL=2897 B) |
ok (Đã xác minh) |
4.3 Hợp đồng 16 Ca Kiểm thử pytest (tests/test_linux_crawler_lab.py)#
Toàn bộ 16/16 ca kiểm thử vượt qua nguyên trạng dưới Python 3.12 (.venv với uv.lock, 16 passed):
| # | Tên Hàm Kiểm thử (test_linux_crawler_lab.py) |
Khẳng định & Bất biến Bắt buộc |
|---|---|---|
| 1 | test_01_posix_umask_resolution_and_special_bits_ls_string |
Kiểm chứng 0666 & ~0022 -> 0644 (-rw-r--r--), 0777 & ~0027 -> 0750 (drwxr-x---), SUID chữ thường s (04755) vs. chữ HOA S (04644). |
| 2 | test_02_sticky_bit_and_directory_rwx_semantics |
Khẳng định 1777 -> drwxrwxrwt, tính trực giao 0111 (duyệt được, ls bị chặn), và bit Sticky chặn non-owner unlink trong khi cho phép chủ tệp và chủ thư mục. |
| 3 | test_03_vfs_deleted_50gb_log_inode_refcount_and_o_append_truncate |
Tái hiện df=50 GiB vs. du=0 sau unlink, chứng minh hard link còn tồn tại khi xóa 1 tên, và kiểm tra thu hồi 0 GiB qua truncate_proc_fd(o_append=True) + close_fd. |
| 4 | test_04_fd_dup2_redirection_left_to_right_order_and_stderr_leak |
Kiểm chứng >out.log 2>&1 chia sẻ 1 struct file, 2>&1 >out.log làm rò stderr ra tty, >out.log 2>out.log dính clobber_race, và |pipe 2>&1 >/dev/null giữ riêng stderr. |
| 5 | test_05_real_makefile_dag_parse_incremental_rebuild_and_parallel_work_span |
Phân tích trực tiếp tệp Makefile thật: khẳng định T1=12.0s, T_inf=7.0s, -j2 đạt 7.0s (>1.5x), và chạm posix_and_make_engine.py bỏ qua raw_pages.json/corpus.jsonl. |
| 6 | test_06_makefile_delete_on_error_prevents_stale_corrupted_artifact |
Chứng minh thiếu .DELETE_ON_ERROR khiến data/corpus.jsonl hỏng bị bỏ qua ở lần chạy kế tiếp; bật .DELETE_ON_ERROR ép xây lại đúng tệp hỏng. |
| 7 | test_07_cron_parser_vixie_dom_or_dow_quirk_and_overlap_stampede |
Phát hiện bẫy DOM OR DOW trên 0 9 13 * 5, kiểm định bước */15, và chứng minh cron chồng lấn 3x (rho=2.5) so với flock=1. |
| 8 | test_08_systemd_timer_jitter_concurrency_collapse_and_psi_calculation |
Xác nhận 100 nút sập đỉnh từ 300 xuống <= 15 (>= 90% giảm đỉnh), khớp Định luật Little 100 * 5 / 45 = 11.11, và hợp nhất khoảng PSI chính xác (full=10.0%). |
| 9 | test_09_url_canonicalization_allowlist_and_ssrf_bypass_rejection |
Chuẩn hóa RFC 3986 (lọc utm_source, sắp xếp query, bỏ :443 & #fragment), bác bỏ file:// và user@host, chặn evil-example.com, example.com.attacker.io, 169.254.169.254. |
| 10 | test_10_authentic_bash_systemd_and_crontab_artifacts_hardening_guards |
Kiểm tra crawl_pipeline.sh (tách SC2155, tôn trọng biến môi trường), fsds-crawler.service (StateDirectory/LogsDirectory/RuntimeDirectory), fsds-crawler.timer, và user crontab.example 5 trường. |
| 11 | test_11_local_http_crawler_sha256_dedup_and_atomic_jsonl_replace |
Thu thập 9 URL trên LocalFixtureServer, lưu 7 tài liệu duy nhất, loại 1 trùng nội dung SHA-256, loại 1 URL tracking, chặn 2 SSRF, ghi JSONL không để lại tệp .tmp. |
| 12 | test_12_cli_crawler_deterministic_exit_codes_0_2_3 |
Xác nhận các mã thoát chuẩn hóa: 0 (thành công), 2 (lỗi tham số/allowlist/file://), 3 (lỗi HTTP với --fail-on-http-error). |
| 13 | test_13_pydantic_contracts_reject_invalid_modes_and_extra_fields |
Xác nhận ValidationError khi truyền khóa lạ/bit tràn vào Pydantic, và kiểm chứng nếu os.replace sập giữa chừng thì tệp cũ vẫn nguyên vẹn và .tmp được dọn sạch. |
| 14 | test_14_cli_demo_workbench_json_and_zero_forbidden_imports |
Chạy end-to-end run_lab_demo.py, kiểm tra đủ 6 KPI, 4 bars, 4 tables trong JSON và quét AST toàn bộ .py bảo đảm 0 import giải tuần tự bị cấm (pickle, joblib, cloudpickle, dill, shelve, marshal). |
| 15 | test_15_ssrf_redirect_301_302_307_308_and_post_dns_blocked |
Kiểm thử validate_target_url (cờ allow_loopback_test mặc định False, giả lập DNS rebinding 169.254.169.254/127.0.0.1) và máy chủ chuyển hướng 301/302/307/308 chứng minh SafeHTTPRedirectHandler chặn sạch SSRF ngay trước khi kết nối chặng tiếp theo. |
| 16 | test_16_graceful_shutdown_sigterm_and_healthcheck |
Kiểm định check_crawler_health (ready vs draining), lắp/khôi phục trình xử lý SIGTERM/SIGINT, và xác nhận crawl_site dừng gọn khi stop_event được bật. |
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 & SOTA 2024–2026 (Curated SOTA Reading List)#
- IEEE & The Open Group / Austin Group (2024). IEEE Std 1003.1-2024 (POSIX.1-2024 / The Open Group Base Specifications Issue 8).
Vì sao quan trọng: Chuẩn hóa chính thứcset -o pipefailvàcd -evào chuẩn POSIX sau hơn hai thập kỷ tồn tại như tiện ích mở rộng riêng của từng shell, đồng thời định nghĩa ranh giới nguyên tửPIPE_BUFvà hành vidup2(2)/rename(2). - Weiner, J., & Heo, T. (Linux Kernel Upstream, 2018–2026). Pressure Stall Information (PSI) (
Documentation/accounting/psi.rst) và Control Group v2 (Documentation/admin-guide/cgroup-v2.rst).
Vì sao quan trọng: Đặt chuẩn định lượngsome/fullcho nghẽn CPU, bộ nhớ và I/O, tạo nền tảng chosystemd-oomdvà hệ điều phối Borg/Meta ngắt thrashing trước khi toàn máy chủ treo cứng. - Gregg, B. (2019) & Starovoitov, A., Borkmann, D., Nakryiko, A. (Linux Kernel
Documentation/bpf/, 2020–2026). BPF Performance Tools và đặc tả BTF / CO-RE (Compile Once – Run Everywhere).
Vì sao quan trọng: Lý giải chênh lệch chi phí10x–100x+củaptrace(strace) so vớieBPFfentry/tracepointở cấp nano-giây và cơ chế di động nhị phân không cần bộ biên dịch trên máy chủ sản xuất. - Poettering, L., et al. (
systemdProject / Freedesktop.org, 2024–2026).systemd.timer(5),systemd.resource-control(5), vàsystemd.exec(5).
Vì sao quan trọng: Chuẩn hóa kỹ thuật lập lịch chống bầy đàn (RandomizedDelaySec,FixedRandomDelay,AccuracySec=1s,Persistent=true), cô lậpcgroups v2(MemoryHigh,MemoryMax,KillMode=mixed) và nhật ký có cấu trúcjournald. - Thomas, G., Gedam, P., Laíns, F., Ingram, D., & Chung, T. (Python Software Foundation,
PEP 600[2019],PEP 656[2021],PEP 668[2023]). Portablemanylinux/musllinuxPlatform Tags & Externally Managed Python Environments.
Vì sao quan trọng: Giải thích nền tảng vì sao Ubuntu 24.04/26.04 chặnpip installtoàn cục (thúc đẩyuv) và vì sao hệ thống AI nên đóng gói trênglibcslim thay vì Alpinemusl.
5.2 Tám Điểm Kiểm tra Tư duy (Q1–Q8) & Sáu Bài tập Trọng số#
- Q1 (
VFS&lsof +L1): Viết phương trình bất biến thu hồi khối đĩa trên inode và giải thích vì saotruncate -s 0 /proc/<pid>/fd/3có thể tạo lỗ thưa50 GiBnếu thiếu cờO_APPEND. - Q2 (
umask&Sticky): Tính tay quyền bát phân và chuỗils -lcủa(0o777, 0o027),(0o644, 0o000, special=0o4000), và giải thích tại sao quyềnw+xtrên thư mục xóa được tệp0444củarootnếu thiếu bit1000. - Q3 (
PID 1& Trạng tháiD/Z): Giải thích cơ chếSIGNAL_UNKILLABLEkhiếnCMD python worker.pychếtExit 137sau30svà phân biệt lý dokill -9thất bại trên cả tiến trìnhDlẫnZ. - Q4 (
dup2&PIPE_BUF): Vẽ trạng tháifdtablevàstruct fileở từng bước của> out.log 2>&1,2>&1 > out.logvà> out.log 2> out.log. - Q5 (
Bash&flock): Chỉ ra vì saolocal res=$(curl ...)pháset -e(SC2155) và chứng minh việc gọirm -f "$LOCK_FILE"trongtrapphá hủy cơ chế khóa loại trừ lẫn nhau củaflock(2). - Q6 (
Makefile& ABI): Giải thích cơ chế.DELETE_ON_ERROR+mv $@.tmp $@bảo vệ pipeline trước dữ liệu cắt cụt, áp dụng cận dưới Brent cho DAG \(T_1=12\text{ s}, T_\infty=7\text{ s}\), và lý giải lỗiGLIBCXX/ phình RSSptmalloc2. - Q7 (
Cronvs.systemd&PSI): Giải thích bẫy0 9 13 * 5, tính mức giảm đỉnh cụm100nút theo Định luật Little khi dùngRandomizedDelaySec=45s, và phân biệtPSIsomevs.full. - Q8 (
CLI Crawler&eBPF): Trình bày bộ quy tắc chuẩn hóa RFC 3986, chống rẽ nhánh SSRF (169.254.169.254), chống trùngSHA-256, ghi nguyên tửos.replace(), và so sánhstracevs.eBPFtrên tải2,000 RPS.
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) — Đại số Quyền POSIX,
umask& Rò rỉ50.0 GiBOpen-FD trênVFS:- Bước thực hành: Gọi
resolve_posix_permissionscho bộ(0o666, 0o022)và(0o777, 0o027); chạycheck_directory_accessvớimode=0o0111(duyệt nhưng khôngls) vàmode=0o1777(Sticky Bit). Tiếp theo khởi tạoVirtualFileSystem, cấp phát tệp50.0 GiBđang mởfd, gọiunlink()rồi so sánh kết quảdfvs.du, cuối cùng đối chiếutruncate_proc_fd(o_append=False)(lỗ thưasparse hole) vớitruncate_proc_fd(o_append=True)+close_fd(). - Tiêu chí đạt: Tính chính xác
0644,0750, xác nhận Sticky Bit chặn non-owner xóa tệp nhưng cho phép chủ sở hữu/chủ thư mục, và giải phóng sạch về0.0 GiBmà không tạo sparse hole.
- Bước thực hành: Gọi
- Bài tập 2 (15 điểm) — Chuỗi
dup2(2), BẫyPID 1& Chống Rách Dữ liệu Khi NhậnSIGTERM:- Bước thực hành: Chạy
simulate_fd_redirectioncho cả 4 tổ hợp (>out.log 2>&1,2>&1 >out.log,>out.log 2>out.log,|pipe 2>&1 >/dev/null). ViếtDockerfilemẫu phân biệt rõ shell formCMD python worker.pyvs. JSON exec formCMD ["python", "worker.py"], bọc bằngENTRYPOINT ["/usr/bin/tini", "--"], và kiểm tra hành viinstall_signal_handlers+atomic_write_jsonltrongcli_crawler.py. - Tiêu chí đạt: Chứng minh đúng
shared_descvà dòng chảystderr, xác nhậnos.replacegiữ nguyên vẹn tệp đích khi dừng đột ngột, và chạy quatest_04,test_13,test_16.
- Bước thực hành: Chạy
- Bài tập 3 (15 điểm) — Bash Strict Mode (
ShellCheckClean),flock(2)&systemd/crontabHardening:- Bước thực hành: Kiểm toán
scripts/crawl_pipeline.sh(tách rời khai báo + gán biến khắc phụcSC2155, staging cùng hệ tệp quamktemp -p, khóaflock -n 9giữ nguyên inode khicleanup), kiểm tradeploy/fsds-crawler.service(DynamicUser=yes,ProtectSystem=strict,StateDirectory,LogsDirectory,RuntimeDirectory) vàdeploy/crontab.examplechuẩn 5 trường*/30 * * * *. - Tiêu chí đạt: Vượt
shellcheck(0 cảnh báoSC2155/SC2086/SC2064) và đạt trọn vẹntest_10.
- Bước thực hành: Kiểm toán
- Bài tập 4 (20 điểm) — Phân tích Đồ thị
MakefileThực, Work–Span-j$(nproc)&.DELETE_ON_ERROR:- Bước thực hành: Dùng
parse_makefilenạp trực tiếp tệpMakefilecủa Lab 01, lập lịch Work–Span quaplan_makefile_rebuild(concurrency=1)vàconcurrency=2(\(T_1=12.0\text{ s}, T_\infty=7.0\text{ s}\)), mô phỏng chạmmtimecủaposix_and_make_engine.py, và kiểm thử kịch bản tiến trình ghidata/corpus.jsonlsập giữa chừng khi bật/tắt.DELETE_ON_ERROR:. - Tiêu chí đạt: Chứng minh chạy lại đúng
2/4mục tiêu (6.0 s, bỏ qua2/4), tăng tốc-j2đạt1.71x, và.DELETE_ON_ERRORép xây lại tệp cắt cụt trongtest_05–test_06.
- Bước thực hành: Dùng
- Bài tập 5 (15 điểm) — Bẫy
CronDOM OR DOW, Định luật Little chosystemdJitter &PSI:- Bước thực hành: Kiểm tra
parse_cron_expression("0 9 13 * 5")phát hiệndom_or_dow_quirk; chạysimulate_cron_vs_systemd_fleetcho cụm100nút (\(\bar{t}=5\text{ s}, T_{\text{period}}=60\text{ s}, J=45\text{ s}\)) đối chiếu kịch bản chồng lấn3xvớiflock=1và jitter; hợp nhất các khoảng nghẽn CPU/RAM trêncompute_psi_pressure. - Tiêu chí đạt: Xác nhận đỉnh đồng thời cụm giảm
-96.0%(300 -> 12), khớp Định luật LittleE[C] = 11.11, và phân tách đúngPSI somevs.fullquatest_07–test_08.
- Bước thực hành: Kiểm tra
- Bài tập 6 (20 điểm) — CLI Website Crawler Chống SSRF Redirect, Healthcheck & Kiểm định
16/16 pytest:- Bước thực hành: Chạy
scripts/run_lab_demo.py --quick --output artifacts/t2_ch01_workbench_results.json, kiểm định đầu dò--healthcheck, kiểm thử chặn SSRF trên các chặng chuyển hướng301/302/307/308và giả lập DNS rebinding tới169.254.169.254, xác minh mã thoát0/2/3, và chạyruff check src tests scripts+pytest -p no:cacheprovider -v. - Tiêu chí đạt: Xuất đủ
6KPI,4biểu đồ,4bảng;ruff0 lỗi;16/16pytestPASS kèm0import giải tuần tự không an toàn (pickle,joblib,cloudpickle,dill,shelve,marshal).
- Bước thực hành: Chạy
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. POSIX Permissions, VFS Refcount & Open-FD Leak | 15 | Tính đúng umask/Sticky Bit (0750, 1777); chứng minh i_nlink=0 & open_fd=0 và xử lý O_APPEND truncate về 0.0 GiB. |
Tests 1, 2, 3 |
2. Luồng FD dup2(2), PID 1 Signal Safety & Bash SC2155 |
20 | Xếp đúng thứ tự > log 2>&1; sửa CMD exec form + tini + SIGTERM; tách SC2155 & staging cùng filesystem trong crawl_pipeline.sh. |
Tests 4, 10, 16 |
3. Makefile DAG Work–Span & .DELETE_ON_ERROR |
20 | Giảm tải incremental đúng 2/4 mục tiêu, đạt T_inf=7.0s (1.71x ở -j2), và chặn tệp cắt cụt nằm lại nhờ .DELETE_ON_ERROR:. |
Tests 5, 6 |
4. Điều phối systemd.timer + cgroups v2 & crontab 5 Trường |
15 | Sửa crontab.example 5 cột; cấu hình StateDirectory/LogsDirectory/RuntimeDirectory; giảm đỉnh cụm 300 -> 12 (-96.0%); tính đúng PSI. |
Tests 7, 8, 10 |
5. CLI Crawler Chống SSRF Redirect, Atomic JSONL & 16/16 pytest |
30 | Chặn 301/302/307/308 SSRF & DNS rebind; mã thoát 0/2/3; uv.lock tái lập; ruff sạch và 16/16 pytest PASS không có import cấm. |
Tests 9, 11–16 + ruff check |
| 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 (đặc biệt 16/16 test bắt buộc phải PASS). |
pytest -p no:cacheprovider -v |
VFS 50 GiB Deleted-Log Lifecycle: df Reported vs du Apparent (GiB)
Simulated Makefile Work-Span DAG Latency (Serial -j1, Parallel -j2, Incremental)
100-Node Fleet Peak Concurrent Workers (Unprotected Cron vs systemd Jitter)
Offline CLI Crawler Funnel (URLs, SHA-256 Unique Docs, Blocked SSRF)
POSIX Bitmask Resolution, Sticky Guard & VFS Open-FD Refcount Audit
| scenario | mode_or_nlink | open_fd_or_sticky | df_vs_du_or_ls | verdict |
|---|---|---|---|---|
| file_default_0666_umask_0022 | 0644 | 110100100 | -rw-r--r-- | OK |
| dir_isolated_0777_umask_0027 | 0750 | 111101000 | drwxr-x--- | OK |
| tmp_sticky_1777_unlink_other | 1777 | owner_ok=True/other_blk=True | drwxrwxrwt | PROTECTED |
| deleted_50g_log_post_rm | i_nlink=0 | open_fd=1 | df=50.0G / du=0.0G | GHOST_LEAK |
| proc_fd_truncate_o_append | i_nlink=0 | closed_reclaimed=True | df=0.0G / hole=False | RECLAIMED |
Bash dup2 FD Routing & Real Makefile Incremental / Crash-Safety Audit
| scenario | fd1_or_rebuilt | fd2_or_skipped | invariant_check | status |
|---|---|---|---|---|
| bash_correct_gt_log_2gt_1 | out.log | out.log | shared_desc=True | SAFE |
| bash_bug_2gt_1_gt_log | out.log | tty | stderr_leaked_tty=True | STDERR_LOST |
| bash_clobber_gt_log_2gt_log | out.log | out.log | clobber_race=True | RACE_CORRUPTION |
| makefile_inc_touch_engine | artifacts/posix_audit.json,artifacts/crawl_report.json | data/raw_pages.json,data/corpus.jsonl | Tp=6.0s (-j2) | MINIMAL_REBUILD |
| makefile_crash_no_del_vs_del | no_del_skip=True | with_del_rebuild=True | real_mk_has_del=True | GUARD_VERIFIED |
Cron Overlap Stampede vs systemd Jitter & cgroups v2 PSI Telemetry
| engine_or_metric | period_or_window | concurrency_or_some | peak_or_full | outcome |
|---|---|---|---|---|
| cron_vixie_quirk_0_9_13_star_5 | DOM=13 & DOW=Fri | quirk_union=True | 61 runs/yr | AMBIGUOUS_OR |
| cron_unprotected_100_nodes | T_p=60s / T_e=150s | single_node=3x | fleet_peak=300 | OOM_STAMPEDE |
| flock_plus_systemd_jitter_45s | J=45s, E[C]=11.11 | single_flock=1 (skip=4) | fleet_peak=12 | -96.0%_PEAK |
| cgroups_v2_psi_healthy | 10.0s window | some=2.5% | full=0.0% | oomd_risk=False |
| cgroups_v2_psi_thrashing | 10.0s window | some=18.4% | full=12.5% | oomd_risk=True |
Offline Ephemeral HTTP CLI Crawler Corpus & Security Boundary Sample
| url_path | status | word_count | sha256_prefix | title |
|---|---|---|---|---|
| / | 200 | 47 | f07361680a09 | FSDS Linux Knowledge Hub |
| /docs/linux | 200 | 36 | df6e9c2d55c0 | Linux VFS, Inodes & POSIX Permissions |
| /docs/bash | 200 | 22 | fc674bf09af8 | Production Bash Strict Mode & flock |
| /docs/makefile | 200 | 20 | 084d02a26221 | Compilation Toolchain & Makefile DAG |
| /docs/systemd | 200 | 18 | a14470bf2956 | systemd Timers, cgroups v2 PSI & eBPF |
| /docs/inode-leak | 200 | 24 | 77ec5ee88f87 | 50 GiB Deleted Log Open-FD Case |
| /docs/permissions | 200 | 21 | 0ff60d0ddb5c | POSIX Modes & umask Algebra |
03-track-2-data-and-ai-engineering/part-01-software-systems-foundations/labs/lab-01-linux-makefile-web-crawler
SHELL := /bin/bash
.SHELLFLAGS := -Eeuo pipefail -c
.DELETE_ON_ERROR:
.ONESHELL:
PYTHON := python3
PYTHONPATH := src
DATA_DIR := data
ARTIFACTS_DIR := artifacts
.PHONY: all crawl extract audit report test lint clean
all: $(ARTIFACTS_DIR)/crawl_report.json
$(DATA_DIR) $(ARTIFACTS_DIR):
mkdir -p $@
$(DATA_DIR)/raw_pages.json: src/linux_crawler_lab/cli_crawler.py | $(DATA_DIR)
PYTHONPATH=$(PYTHONPATH) $(PYTHON) -m linux_crawler_lab.cli_crawler --serve-fixtures --max-pages 8 --output-raw $@.tmp
mv -f $@.tmp $@
$(DATA_DIR)/corpus.jsonl: $(DATA_DIR)/raw_pages.json src/linux_crawler_lab/cli_crawler.py | $(DATA_DIR)
PYTHONPATH=$(PYTHONPATH) $(PYTHON) -m linux_crawler_lab.cli_crawler --serve-fixtures --max-pages 8 --output-jsonl $@.tmp
test -s $@.tmp
mv -f $@.tmp $@
$(ARTIFACTS_DIR)/posix_audit.json: src/linux_crawler_lab/posix_and_make_engine.py | $(ARTIFACTS_DIR)
PYTHONPATH=$(PYTHONPATH) $(PYTHON) scripts/run_lab_demo.py --quick --output $@.tmp
mv -f $@.tmp $@
$(ARTIFACTS_DIR)/crawl_report.json: $(DATA_DIR)/corpus.jsonl $(ARTIFACTS_DIR)/posix_audit.json | $(ARTIFACTS_DIR)
PYTHONPATH=$(PYTHONPATH) $(PYTHON) -m linux_crawler_lab.cli_crawler --serve-fixtures --max-pages 8 --report-json $@.tmp
mv -f $@.tmp $@
crawl: $(DATA_DIR)/raw_pages.json
extract: $(DATA_DIR)/corpus.jsonl
audit: $(ARTIFACTS_DIR)/posix_audit.json
report: $(ARTIFACTS_DIR)/crawl_report.json
test:
$(PYTHON) -m pytest -v
lint:
shellcheck scripts/crawl_pipeline.sh
clean:
rm -rf $(DATA_DIR)/*.json $(DATA_DIR)/*.jsonl $(DATA_DIR)/*.tmp $(ARTIFACTS_DIR)/*.tmp $(ARTIFACTS_DIR)/posix_audit.json $(ARTIFACTS_DIR)/crawl_report.json
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit 2>/dev/null || true
IFS=$'\n\t'
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
readonly SCRIPT_DIR
LAB_ROOT="$(cd -- "${SCRIPT_DIR}/.." && pwd -P)"
readonly LAB_ROOT
LOCK_FILE="${LOCK_FILE:-/tmp/fsds-crawler.lock}"
readonly LOCK_FILE
OUTPUT_JSONL="${OUTPUT_JSONL:-${LAB_ROOT}/data/corpus.jsonl}"
readonly OUTPUT_JSONL
REPORT_JSON="${REPORT_JSON:-${LAB_ROOT}/artifacts/crawl_report.json}"
readonly REPORT_JSON
LOG_FILE="${LOG_FILE:-${LAB_ROOT}/artifacts/crawl_pipeline.log}"
readonly LOG_FILE
PYTHON_BIN="${PYTHON_BIN:-python3}"
readonly PYTHON_BIN
tmpdir=""
stage_jsonl=""
stage_report=""
cleanup() {
local rc=$?
trap - EXIT INT TERM
if [[ -n "$stage_jsonl" && -f "$stage_jsonl" ]]; then
rm -f -- "$stage_jsonl"
fi
if [[ -n "$stage_report" && -f "$stage_report" ]]; then
rm -f -- "$stage_report"
fi
if [[ -n "$tmpdir" && -d "$tmpdir" ]]; then
rm -rf -- "$tmpdir"
fi
exit "$rc"
}
trap cleanup EXIT INT TERM
main() {
local out_dir
out_dir="$(dirname -- "$OUTPUT_JSONL")"
local report_dir
report_dir="$(dirname -- "$REPORT_JSON")"
mkdir -p -- "$(dirname -- "$LOCK_FILE")" "$out_dir" "$report_dir" "$(dirname -- "$LOG_FILE")"
tmpdir="$(mktemp -d)"
# Kernel-managed advisory FD lock: auto-released even on SIGKILL/OOM (never unlink lockfile!)
exec 9>"$LOCK_FILE"
if ! flock -n 9; then
printf '%s [SKIP] previous crawl run still holds flock=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$LOCK_FILE" >> "$LOG_FILE" 2>&1
exit 0
fi
# Stage temp files on the SAME filesystem as targets so mv -f performs an atomic rename(2) (no EXDEV)
stage_jsonl="$(mktemp -p "$out_dir" .corpus.jsonl.XXXXXX)"
stage_report="$(mktemp -p "$report_dir" .crawl_report.json.XXXXXX)"
# Canonical left-to-right redirection (> file 2>&1) binds both fd1 and fd2 to LOG_FILE
{
printf '%s [START] running offline-safe CLI crawler pipeline\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
PYTHONPATH="${LAB_ROOT}/src" "$PYTHON_BIN" -m linux_crawler_lab.cli_crawler \
--serve-fixtures \
--max-pages 8 \
--output-jsonl "$stage_jsonl" \
--report-json "$stage_report"
mv -f -- "$stage_jsonl" "$OUTPUT_JSONL"
stage_jsonl=""
mv -f -- "$stage_report" "$REPORT_JSON"
stage_report=""
printf '%s [DONE] atomic promote complete -> %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$OUTPUT_JSONL"
} > "$LOG_FILE" 2>&1
}
main "$@"
[Unit]
Description=FSDS-SOTA-2026 CLI Website Crawler Worker (Hardened cgroups v2 Service)
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
Environment="PATH=/opt/fsds/.venv/bin:/usr/local/bin:/usr/bin:/bin"
Environment="PYTHONUNBUFFERED=1"
Environment=OUTPUT_JSONL=/var/lib/fsds-crawler/corpus.jsonl
Environment=REPORT_JSON=/var/lib/fsds-crawler/report.json
Environment=LOG_FILE=/var/log/fsds-crawler/crawl.log
Environment=LOCK_FILE=/run/fsds-crawler/crawl.lock
WorkingDirectory=/opt/fsds/lab-01-linux-makefile-web-crawler
# crawl_pipeline.sh acquires flock -n 9 on LOCK_FILE inside RuntimeDirectory
ExecStart=/opt/fsds/lab-01-linux-makefile-web-crawler/scripts/crawl_pipeline.sh
# Least-privilege namespace sandboxing
DynamicUser=yes
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=read-only
PrivateTmp=yes
StateDirectory=fsds-crawler
LogsDirectory=fsds-crawler
RuntimeDirectory=fsds-crawler
# cgroups v2 blast-radius containment
MemoryHigh=384M
MemoryMax=512M
CPUQuota=100%
TasksMax=64
TimeoutStartSec=120s
TimeoutStopSec=30s
KillMode=mixed
# Structured journald telemetry
StandardOutput=journal
StandardError=journal
SyslogIdentifier=fsds-crawler
[Unit]
Description=FSDS-SOTA-2026 CLI Website Crawler Periodic Timer (Jitter + Catch-Up)
[Timer]
OnCalendar=*-*-* *:00/5:00
RandomizedDelaySec=45s
FixedRandomDelay=true
AccuracySec=1s
Persistent=true
Unit=fsds-crawler.service
[Install]
WantedBy=timers.target
# Hardened production user crontab example (legacy baseline when systemd is unavailable)
# Note: User crontabs (crontab -e) use 5 time columns WITHOUT a username column
# (unlike system-wide /etc/crontab or /etc/cron.d/* files).
SHELL=/bin/bash
PATH=/opt/fsds/.venv/bin:/usr/local/bin:/usr/bin:/bin
MAILTO=""
# 1. Explicit PATH + flock -n overlap guard + canonical > log 2>&1 redirection
# Note: escape % as \% in cron commands if formatting dates!
*/30 * * * * /usr/bin/flock -n /run/lock/fsds-crawler.lock /opt/fsds/lab-01-linux-makefile-web-crawler/scripts/crawl_pipeline.sh > /var/log/fsds-crawler.log 2>&1
# ANTI-PATTERN 1 (BROKEN): 2>&1 > /var/log/fsds-crawler.log
# Evaluates left-to-right: fd2 binds to cron pipe BEFORE fd1 opens the log file, losing stderr tracebacks!
# ANTI-PATTERN 2 (BROKEN): 0 9 13 * 5 ...
# Vixie cron DOM-OR-DOW quirk triggers on EVERY 13th day of month OR EVERY Friday (~61 runs/yr), not Friday the 13th!
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "linux-crawler-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 Lab 01: GNU/Linux Internals, Shell, Makefile DAG, Scheduling & CLI Website Crawler"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
]
[project.scripts]
fsds-crawler = "linux_crawler_lab.cli_crawler:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
[tool.ruff]
target-version = "py312"
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP", "S", "RUF"]
ignore = ["E501", "S101", "S104", "S310"]
[tool.ruff.lint.per-file-ignores]
"tests/*.py" = ["S603"]
"""FSDS-SOTA-2026 Track 2 Lab 01: GNU/Linux Internals, Makefile DAG, Scheduling & CLI Crawler."""
from linux_crawler_lab.cli_crawler import (
CrawledDocument,
CrawlReport,
LocalFixtureServer,
SafeHTTPRedirectHandler,
SSRFBlockedError,
atomic_write_json,
atomic_write_jsonl,
atomic_write_text,
canonicalize_url,
check_crawler_health,
crawl_site,
extract_html_text_and_links,
install_signal_handlers,
is_url_allowed,
restore_signal_handlers,
validate_target_url,
)
from linux_crawler_lab.cli_crawler import (
main as cli_main,
)
from linux_crawler_lab.posix_and_make_engine import (
CronScheduleSpec,
MakefileRuleSpec,
PosixPermissionSpec,
VirtualFileSystem,
check_directory_access,
compute_psi_pressure,
parse_cron_expression,
parse_makefile,
plan_makefile_rebuild,
resolve_posix_permissions,
simulate_cron_vs_systemd_fleet,
simulate_fd_redirection,
)
__all__ = [
"CrawlReport",
"CrawledDocument",
"CronScheduleSpec",
"LocalFixtureServer",
"MakefileRuleSpec",
"PosixPermissionSpec",
"SSRFBlockedError",
"SafeHTTPRedirectHandler",
"VirtualFileSystem",
"atomic_write_json",
"atomic_write_jsonl",
"atomic_write_text",
"canonicalize_url",
"check_crawler_health",
"check_directory_access",
"cli_main",
"compute_psi_pressure",
"crawl_site",
"extract_html_text_and_links",
"install_signal_handlers",
"is_url_allowed",
"parse_cron_expression",
"parse_makefile",
"plan_makefile_rebuild",
"resolve_posix_permissions",
"restore_signal_handlers",
"simulate_cron_vs_systemd_fleet",
"simulate_fd_redirection",
"validate_target_url",
]
"""Deterministic GNU/Linux internals, POSIX/VFS, FD redirection, Makefile DAG & scheduler engine."""
from __future__ import annotations
import math
import re
from collections import deque
from dataclasses import dataclass, field
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, field_validator
class PosixPermissionSpec(BaseModel):
"""Typed boundary contract for POSIX permission bits and process umask."""
model_config = ConfigDict(frozen=True, extra="forbid")
base_mode: int = Field(default=0o666, ge=0, le=0o777)
umask: int = Field(default=0o022, ge=0, le=0o777)
is_dir: bool = False
special_bits: int = Field(default=0, ge=0, le=0o7000)
@field_validator("special_bits")
@classmethod
def _validate_special_bits(cls, value: int) -> int:
if value & ~0o7000:
raise ValueError("special_bits may only set bits in 0o7000 (SUID/SGID/Sticky).")
return value
class MakefileRuleSpec(BaseModel):
"""Typed representation of one parsed GNU Makefile rule."""
model_config = ConfigDict(frozen=True, extra="forbid")
target: str = Field(min_length=1)
prerequisites: tuple[str, ...] = ()
order_only: tuple[str, ...] = ()
recipes: tuple[str, ...] = ()
is_phony: bool = False
line_number: int = Field(default=1, ge=1)
class CronScheduleSpec(BaseModel):
"""Typed contract for 5-field cron & fleet scheduling simulations."""
model_config = ConfigDict(frozen=True, extra="forbid")
expression: str = Field(min_length=9)
period_sec: float = Field(gt=0.0)
exec_sec: float = Field(gt=0.0)
fleet_nodes: int = Field(ge=1, le=100_000)
jitter_sec: float = Field(ge=0.0)
def _format_rwx_triplet(bits: int, special_char: str | None = None) -> str:
chars = [
"r" if (bits & 0b100) else "-",
"w" if (bits & 0b010) else "-",
"x" if (bits & 0b001) else "-",
]
if special_char is not None:
chars[2] = special_char.lower() if (bits & 0b001) else special_char.upper()
return "".join(chars)
def resolve_posix_permissions(
base_mode: int,
umask: int,
is_dir: bool = False,
special_bits: int = 0,
) -> dict[str, Any]:
"""Compute effective POSIX mode via base_mode & (~umask & 0o777) and ls -l string."""
spec = PosixPermissionSpec(
base_mode=base_mode,
umask=umask,
is_dir=is_dir,
special_bits=special_bits,
)
rwx_effective = spec.base_mode & ((~spec.umask) & 0o777)
full_mode = rwx_effective | (spec.special_bits & 0o7000)
suid = bool(full_mode & 0o4000)
sgid = bool(full_mode & 0o2000)
sticky = bool(full_mode & 0o1000)
u_bits = (full_mode >> 6) & 0b111
g_bits = (full_mode >> 3) & 0b111
o_bits = full_mode & 0b111
prefix = "d" if spec.is_dir else "-"
ls_str = (
prefix
+ _format_rwx_triplet(u_bits, "s" if suid else None)
+ _format_rwx_triplet(g_bits, "s" if sgid else None)
+ _format_rwx_triplet(o_bits, "t" if sticky else None)
)
return {
"base_octal": f"{spec.base_mode:04o}",
"umask_octal": f"{spec.umask:04o}",
"effective_mode": full_mode,
"octal_str": f"{full_mode:04o}",
"ls_string": ls_str,
"suid": suid,
"sgid": sgid,
"sticky": sticky,
"binary_rwx": f"{rwx_effective:09b}",
}
def check_directory_access(
dir_mode: int,
op: Literal["list", "traverse", "unlink"],
dir_uid: int,
file_uid: int,
caller_uid: int,
caller_class: Literal["owner", "group", "other"] = "other",
) -> bool:
"""Enforce POSIX directory r/w/x orthogonality and Sticky bit (01000) unlink guard."""
if caller_uid == 0:
return True
shift = {"owner": 6, "group": 3, "other": 0}[caller_class]
bits = (dir_mode >> shift) & 0b111
has_r = bool(bits & 0b100)
has_w = bool(bits & 0b010)
has_x = bool(bits & 0b001)
if op == "list":
return has_r
if op == "traverse":
return has_x
if op == "unlink":
if not (has_w and has_x):
return False
if dir_mode & 0o1000:
return caller_uid == dir_uid or caller_uid == file_uid
return True
raise ValueError(f"Unsupported directory operation: {op}")
@dataclass(slots=True)
class _InodeEntry:
inode_id: int
kind: Literal["file", "symlink"]
size_bytes: int = 0
allocated_bytes: int = 0
nlink: int = 0
open_fd_count: int = 0
symlink_target: str | None = None
reclaimed: bool = False
@dataclass(slots=True)
class _OpenFileDescription:
inode_id: int
original_path: str
o_append: bool = True
f_pos: int = 0
@dataclass
class VirtualFileSystem:
"""In-memory POSIX VFS model tracking dentries, inodes, i_nlink & open-FD refcounts."""
_next_inode_id: int = 1001
_inodes: dict[int, _InodeEntry] = field(default_factory=dict)
_dentries: dict[str, int] = field(default_factory=dict)
_open_fds: dict[tuple[int, int], _OpenFileDescription] = field(default_factory=dict)
def _resolve_path(self, path: str, follow_symlinks: bool = True) -> int:
seen: set[str] = set()
curr = path
while True:
if curr not in self._dentries:
raise FileNotFoundError(f"No such file or directory: {curr}")
ino_id = self._dentries[curr]
inode = self._inodes[ino_id]
if inode.kind == "symlink" and follow_symlinks:
if curr in seen or len(seen) >= 40:
raise OSError(f"Too many levels of symbolic links: {path}")
seen.add(curr)
assert inode.symlink_target is not None
curr = inode.symlink_target
continue
return ino_id
def create_file(self, path: str, size_bytes: int = 0) -> int:
if path in self._dentries:
raise FileExistsError(f"Path already exists: {path}")
if size_bytes < 0:
raise ValueError("size_bytes must be non-negative.")
ino_id = self._next_inode_id
self._next_inode_id += 1
self._inodes[ino_id] = _InodeEntry(
inode_id=ino_id,
kind="file",
size_bytes=size_bytes,
allocated_bytes=size_bytes,
nlink=1,
)
self._dentries[path] = ino_id
return ino_id
def hard_link(self, existing_path: str, new_path: str) -> int:
if new_path in self._dentries:
raise FileExistsError(f"Destination exists: {new_path}")
ino_id = self._resolve_path(existing_path, follow_symlinks=False)
inode = self._inodes[ino_id]
if inode.kind != "file":
raise PermissionError("Cannot create hard link to non-regular file in this model.")
inode.nlink += 1
self._dentries[new_path] = ino_id
return ino_id
def symlink(self, target_path: str, link_path: str) -> int:
if link_path in self._dentries:
raise FileExistsError(f"Link path exists: {link_path}")
ino_id = self._next_inode_id
self._next_inode_id += 1
self._inodes[ino_id] = _InodeEntry(
inode_id=ino_id,
kind="symlink",
size_bytes=len(target_path.encode("utf-8")),
allocated_bytes=0,
nlink=1,
symlink_target=target_path,
)
self._dentries[link_path] = ino_id
return ino_id
def open_fd(self, pid: int, path: str, o_append: bool = True) -> int:
ino_id = self._resolve_path(path, follow_symlinks=True)
inode = self._inodes[ino_id]
used_fds = {fd for (p, fd) in self._open_fds if p == pid}
next_fd = 3
while next_fd in used_fds:
next_fd += 1
inode.open_fd_count += 1
self._open_fds[(pid, next_fd)] = _OpenFileDescription(
inode_id=ino_id,
original_path=path,
o_append=o_append,
f_pos=inode.size_bytes if o_append else 0,
)
return next_fd
def write_fd(self, pid: int, fd: int, num_bytes: int) -> int:
if num_bytes < 0:
raise ValueError("num_bytes must be non-negative.")
desc = self._open_fds[(pid, fd)]
inode = self._inodes[desc.inode_id]
if desc.o_append:
desc.f_pos = inode.size_bytes
end_pos = desc.f_pos + num_bytes
if end_pos > inode.size_bytes:
inode.size_bytes = end_pos
inode.allocated_bytes += num_bytes
desc.f_pos = end_pos
return inode.size_bytes
def _try_reclaim(self, inode: _InodeEntry) -> bool:
if not inode.reclaimed and inode.nlink == 0 and inode.open_fd_count == 0:
inode.size_bytes = 0
inode.allocated_bytes = 0
inode.reclaimed = True
return True
return False
def unlink(self, path: str) -> dict[str, Any]:
if path not in self._dentries:
raise FileNotFoundError(f"Path not found: {path}")
ino_id = self._dentries.pop(path)
inode = self._inodes[ino_id]
inode.nlink = max(0, inode.nlink - 1)
reclaimed = self._try_reclaim(inode)
return {
"inode_id": ino_id,
"nlink": inode.nlink,
"open_fd_count": inode.open_fd_count,
"reclaimed": reclaimed,
"allocated_bytes_remaining": inode.allocated_bytes,
}
def truncate_proc_fd(self, pid: int, fd: int) -> dict[str, Any]:
desc = self._open_fds[(pid, fd)]
inode = self._inodes[desc.inode_id]
freed_bytes = inode.allocated_bytes
inode.size_bytes = 0
inode.allocated_bytes = 0
if desc.o_append:
desc.f_pos = 0
return {
"pid": pid,
"fd": fd,
"inode_id": inode.inode_id,
"freed_bytes": freed_bytes,
"o_append": desc.o_append,
"f_pos_after": desc.f_pos,
"sparse_hole_risk": not desc.o_append and desc.f_pos > 0,
}
def close_fd(self, pid: int, fd: int) -> bool:
desc = self._open_fds.pop((pid, fd))
inode = self._inodes[desc.inode_id]
inode.open_fd_count = max(0, inode.open_fd_count - 1)
return self._try_reclaim(inode)
def df_used_bytes(self) -> int:
return sum(ino.allocated_bytes for ino in self._inodes.values() if not ino.reclaimed)
def du_apparent_bytes(self) -> int:
seen_inodes: set[int] = set()
total = 0
for ino_id in self._dentries.values():
if ino_id in seen_inodes:
continue
seen_inodes.add(ino_id)
inode = self._inodes[ino_id]
if inode.kind == "file":
total += inode.size_bytes
return total
def lsof_deleted_open(self) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for (pid, fd), desc in sorted(self._open_fds.items()):
inode = self._inodes[desc.inode_id]
if inode.nlink == 0:
rows.append(
{
"pid": pid,
"fd": fd,
"inode_id": inode.inode_id,
"nlink": inode.nlink,
"size_bytes": inode.size_bytes,
"allocated_bytes": inode.allocated_bytes,
"name": f"{desc.original_path} (deleted)",
}
)
return rows
def simulate_fd_redirection(ops: list[str]) -> dict[str, Any]:
"""Model POSIX shell left-to-right dup2() FD 0/1/2 redirection evaluation."""
has_pipe = "|pipe" in ops
redirs = [op for op in ops if op != "|pipe"]
fd1_target = "pipe_write" if has_pipe else "tty"
fd2_target = "tty"
desc1 = "pipe_desc#0" if has_pipe else "tty_desc#0"
desc2 = "tty_desc#0"
file_counter = 0
trace_steps: list[dict[str, str]] = [
{"op": "INIT" + (" (|pipe)" if has_pipe else ""), "fd1": fd1_target, "fd2": fd2_target, "desc1": desc1, "desc2": desc2}
]
for op in redirs:
clean = op.strip()
if clean == "2>&1":
fd2_target = fd1_target
desc2 = desc1
elif clean == "1>&2":
fd1_target = fd2_target
desc1 = desc2
elif clean.startswith("&>"):
target = clean[2:].strip()
file_counter += 1
fd1_target = target
fd2_target = target
desc1 = f"file_desc#{file_counter}({target})"
desc2 = desc1
elif clean.startswith("2>"):
target = clean[2:].strip()
file_counter += 1
fd2_target = target
desc2 = f"file_desc#{file_counter}({target})"
elif clean.startswith("1>") or clean.startswith(">"):
target = clean[2:].strip() if clean.startswith("1>") else clean[1:].strip()
file_counter += 1
fd1_target = target
desc1 = f"file_desc#{file_counter}({target})"
else:
raise ValueError(f"Unsupported redirection token: {op}")
trace_steps.append(
{"op": clean, "fd1": fd1_target, "fd2": fd2_target, "desc1": desc1, "desc2": desc2}
)
return {
"fd_1_target": fd1_target,
"fd_2_target": fd2_target,
"shared_open_file_description": desc1 == desc2,
"clobber_race": (fd1_target == fd2_target) and (desc1 != desc2),
"stderr_leaked_to_tty": (fd2_target == "tty") and (fd1_target != "tty"),
"trace_steps": trace_steps,
}
_VAR_REF_RE = re.compile(r"\$\(([A-Za-z_][A-Za-z0-9_]*)\)")
_ASSIGN_RE = re.compile(r"^([A-Za-z_.][A-Za-z0-9_.]*)\s*(:=|\?=|\+=|=)\s*(.*)$")
def _expand_make_vars(text: str, variables: dict[str, str]) -> str:
prev = text
for _ in range(10):
curr = _VAR_REF_RE.sub(lambda m: variables.get(m.group(1), m.group(0)), prev)
if curr == prev:
break
prev = curr
return prev
def parse_makefile(makefile_text: str) -> dict[str, Any]:
"""Parse GNU Makefile rules, .PHONY, .DELETE_ON_ERROR, SHELL and variables into typed DAG specs."""
variables: dict[str, str] = {}
phony_targets: set[str] = set()
delete_on_error = False
oneshell = False
shell = "/bin/sh"
shellflags = "-c"
raw_rules: list[dict[str, Any]] = []
current_rule: dict[str, Any] | None = None
for lineno, raw_line in enumerate(makefile_text.splitlines(), start=1):
if raw_line.startswith("\t") and current_rule is not None:
current_rule["recipes"].append(raw_line.lstrip("\t"))
continue
stripped = raw_line.strip()
if not stripped or stripped.startswith("#"):
continue
current_rule = None
assign_m = _ASSIGN_RE.match(stripped)
if assign_m and not stripped.startswith("."):
name, op, val = assign_m.group(1), assign_m.group(2), assign_m.group(3).strip()
expanded = _expand_make_vars(val, variables)
if op == "?=":
variables.setdefault(name, expanded)
elif op == "+=":
variables[name] = f"{variables.get(name, '')} {expanded}".strip()
else:
variables[name] = expanded
if name == "SHELL":
shell = expanded
continue
if ":" not in stripped:
continue
lhs_raw, rhs_raw = stripped.split(":", 1)
lhs = _expand_make_vars(lhs_raw.strip(), variables)
rhs = _expand_make_vars(rhs_raw.strip(), variables)
if lhs == ".PHONY":
phony_targets.update(tok for tok in rhs.split() if tok)
continue
if lhs == ".DELETE_ON_ERROR":
delete_on_error = True
continue
if lhs == ".ONESHELL":
oneshell = True
continue
if lhs == ".SHELLFLAGS":
flags_assign = rhs.lstrip("= ").strip()
shellflags = flags_assign
continue
if "|" in rhs:
normal_part, order_part = rhs.split("|", 1)
else:
normal_part, order_part = rhs, ""
prereqs = tuple(tok for tok in normal_part.split() if tok)
order_only = tuple(tok for tok in order_part.split() if tok)
targets = [tok for tok in lhs.split() if tok]
for idx, tgt in enumerate(targets):
rule_obj = {
"target": tgt,
"prerequisites": prereqs,
"order_only": order_only,
"recipes": [],
"line_number": lineno,
}
raw_rules.append(rule_obj)
if idx == len(targets) - 1:
current_rule = rule_obj
rules: dict[str, MakefileRuleSpec] = {}
for item in raw_rules:
tgt = item["target"]
rules[tgt] = MakefileRuleSpec(
target=tgt,
prerequisites=item["prerequisites"],
order_only=item["order_only"],
recipes=tuple(item["recipes"]),
is_phony=(tgt in phony_targets),
line_number=item["line_number"],
)
return {
"variables": variables,
"phony_targets": sorted(phony_targets),
"delete_on_error": delete_on_error,
"oneshell": oneshell,
"shell": shell,
"shellflags": shellflags,
"rules": rules,
}
def plan_makefile_rebuild(
rules: dict[str, MakefileRuleSpec],
mtimes: dict[str, float | None],
goal: str = "all",
jobs: int = 1,
work_estimates: dict[str, float] | None = None,
failed_target: str | None = None,
delete_on_error: bool = True,
failure_timestamp: float = 9999.0,
) -> dict[str, Any]:
"""Compute topological order, incremental mtime rebuild plan, Work-Span bounds, and crash artifact state."""
if goal not in rules:
raise KeyError(f"Unknown Makefile goal: {goal}")
if jobs < 1:
raise ValueError("jobs (-j) must be >= 1.")
reachable: set[str] = set()
stack = [goal]
while stack:
node = stack.pop()
if node in reachable:
continue
reachable.add(node)
if node in rules:
for dep in rules[node].prerequisites:
stack.append(dep)
# Kahn topological sort over reachable subgraph (u -> v when v depends on u)
in_deg: dict[str, int] = {n: 0 for n in reachable}
adj: dict[str, list[str]] = {n: [] for n in reachable}
for n in reachable:
if n in rules:
for dep in rules[n].prerequisites:
adj[dep].append(n)
in_deg[n] += 1
queue: deque[str] = deque(sorted(n for n, d in in_deg.items() if d == 0))
topo_order: list[str] = []
while queue:
u = queue.popleft()
topo_order.append(u)
for v in sorted(adj[u]):
in_deg[v] -= 1
if in_deg[v] == 0:
queue.append(v)
if len(topo_order) != len(reachable):
raise ValueError("Dependency cycle detected in Makefile DAG.")
rebuilt_map: dict[str, bool] = {}
rebuilt_targets: list[str] = []
skipped_targets: list[str] = []
updated_mtimes = dict(mtimes)
weights = work_estimates or {}
def _node_work(node: str) -> float:
if node not in rules:
return 0.0
if node in weights:
return float(weights[node])
return 0.0 if (rules[node].is_phony and not rules[node].recipes) else 1.0
# Evaluate incremental rebuild predicate in topological order
blocked_by_failure = False
for node in topo_order:
if node not in rules:
rebuilt_map[node] = False
continue
rule = rules[node]
dep_rebuilt = any(rebuilt_map.get(dep, False) for dep in rule.prerequisites)
t_mtime = updated_mtimes.get(node)
if rule.is_phony:
should_run = bool(rule.recipes) or dep_rebuilt
else:
dep_mtimes = [
float(m)
for dep in rule.prerequisites
if (m := updated_mtimes.get(dep)) is not None
]
newer_prereq = any(t_mtime is None or m > float(t_mtime) for m in dep_mtimes)
should_run = (t_mtime is None) or dep_rebuilt or newer_prereq
if blocked_by_failure:
rebuilt_map[node] = False
continue
if should_run:
rebuilt_targets.append(node)
rebuilt_map[node] = True
if failed_target is not None and node == failed_target:
blocked_by_failure = True
if delete_on_error:
updated_mtimes[node] = None
else:
# Shell `> target` updated mtime to now before failing mid-stream!
updated_mtimes[node] = failure_timestamp
elif not rule.is_phony:
prereq_mtimes = [
float(m)
for d in rule.prerequisites
if (m := updated_mtimes.get(d)) is not None
]
max_dep = max(prereq_mtimes, default=0.0)
self_mtime = updated_mtimes.get(node)
prev_self = float(self_mtime) if self_mtime is not None else 0.0
updated_mtimes[node] = max(prev_self, max_dep) + 1.0
else:
rebuilt_map[node] = False
if not rule.is_phony:
skipped_targets.append(node)
# Full-DAG Work (T1), Critical Path Span (T_inf), and list-scheduled T_p
rule_nodes = [n for n in topo_order if n in rules]
earliest_finish: dict[str, float] = {}
for n in topo_order:
deps = rules[n].prerequisites if n in rules else ()
start_t = max((earliest_finish.get(d, 0.0) for d in deps), default=0.0)
earliest_finish[n] = start_t + _node_work(n)
full_t1 = sum(_node_work(n) for n in rule_nodes)
full_t_inf = max((earliest_finish[n] for n in rule_nodes), default=0.0)
# Greedy list scheduling over rebuilt_targets only
rebuilt_set = set(rebuilt_targets)
rem_deps = {
n: {d for d in (rules[n].prerequisites if n in rules else ()) if d in rebuilt_set}
for n in rebuilt_set
}
ready = sorted([n for n, ds in rem_deps.items() if not ds])
active: list[tuple[float, str]] = []
now = 0.0
while ready or active:
while len(active) < jobs and ready:
nxt = ready.pop(0)
active.append((now + _node_work(nxt), nxt))
if not active:
break
active.sort(key=lambda pair: pair[0])
finish_t, finished_node = active.pop(0)
now = finish_t
for cand in sorted(rebuilt_set):
if finished_node in rem_deps[cand]:
rem_deps[cand].remove(finished_node)
if not rem_deps[cand]:
ready.append(cand)
ready.sort()
rebuilt_t1 = sum(_node_work(n) for n in rebuilt_targets)
rebuilt_tp = now
speedup = (rebuilt_t1 / rebuilt_tp) if rebuilt_tp > 0 else 1.0
return {
"goal": goal,
"topo_order": topo_order,
"rebuilt_targets": rebuilt_targets,
"skipped_targets": skipped_targets,
"updated_mtimes": updated_mtimes,
"failed_target_aborted": blocked_by_failure,
"full_dag_t1": round(full_t1, 4),
"full_dag_t_inf": round(full_t_inf, 4),
"rebuilt_t1": round(rebuilt_t1, 4),
"rebuilt_tp": round(rebuilt_tp, 4),
"parallel_speedup": round(speedup, 4),
"brent_lower_bound": round(max(full_t1 / jobs, full_t_inf), 4),
}
def _parse_cron_field(token: str, min_val: int, max_val: int, is_dow: bool = False) -> list[int]:
values: set[int] = set()
for part in token.split(","):
if "/" in part:
base, step_str = part.split("/", 1)
step = int(step_str)
if step <= 0:
raise ValueError(f"Cron step must be > 0: {part}")
else:
base, step = part, 1
if base == "*":
lo, hi = min_val, max_val
elif "-" in base:
lo_s, hi_s = base.split("-", 1)
lo, hi = int(lo_s), int(hi_s)
else:
val = int(base)
lo, hi = val, (max_val if "/" in part else val)
if lo < min_val or hi > max_val or lo > hi:
raise ValueError(f"Cron field out of range [{min_val}, {max_val}]: {part}")
for v in range(lo, hi + 1, step):
values.add(0 if (is_dow and v == 7) else v)
return sorted(values)
def parse_cron_expression(expr: str) -> dict[str, Any]:
"""Validate 5-field crontab expression and detect Vixie DOM-OR-DOW union quirk."""
fields = expr.strip().split()
if len(fields) != 5:
raise ValueError(f"Cron expression must have exactly 5 fields, got {len(fields)}: {expr!r}")
min_f, hour_f, dom_f, mon_f, dow_f = fields
minutes = _parse_cron_field(min_f, 0, 59)
hours = _parse_cron_field(hour_f, 0, 23)
doms = _parse_cron_field(dom_f, 1, 31)
months = _parse_cron_field(mon_f, 1, 12)
dows = _parse_cron_field(dow_f, 0, 7, is_dow=True)
dom_or_dow_quirk = (dom_f != "*") and (dow_f != "*")
return {
"expression": expr.strip(),
"minutes": minutes,
"hours": hours,
"doms": doms,
"months": months,
"dows": dows,
"dom_or_dow_quirk": dom_or_dow_quirk,
}
def simulate_cron_vs_systemd_fleet(
period_sec: float = 60.0,
exec_sec: float = 150.0,
fleet_nodes: int = 100,
jitter_sec: float = 45.0,
horizon_sec: float = 300.0,
cron_expr: str = "* * * * *",
nominal_fleet_exec_sec: float = 5.0,
) -> dict[str, Any]:
"""Compare single-node cron overlap stampede vs flock-guarded & systemd RandomizedDelaySec fleet."""
spec = CronScheduleSpec(
expression=cron_expr,
period_sec=period_sec,
exec_sec=exec_sec,
fleet_nodes=fleet_nodes,
jitter_sec=jitter_sec,
)
parse_cron_expression(spec.expression)
# 1. Single-node unprotected cron overlap math over [0, horizon_sec]
num_ticks = math.floor(horizon_sec / spec.period_sec) + 1
cron_single_starts = [k * spec.period_sec for k in range(num_ticks)]
def _active_at(starts: list[float], t: float, dur: float) -> int:
return sum(1 for s in starts if s <= t < s + dur)
sample_times = [float(t) for t in range(int(horizon_sec) + 1)]
single_cron_peak = max(_active_at(cron_single_starts, t, spec.exec_sec) for t in sample_times)
rho = spec.exec_sec / spec.period_sec
# 2. Single-node flock -n overlap guard: skip tick if previous run is active
flock_starts: list[float] = []
flock_skipped = 0
busy_until = -1.0
for s in cron_single_starts:
if s < busy_until:
flock_skipped += 1
else:
flock_starts.append(s)
busy_until = s + spec.exec_sec
single_flock_peak = max(_active_at(flock_starts, t, spec.exec_sec) for t in sample_times)
# 3. Fleet thundering herd comparison (nominal_fleet_exec_sec across fleet_nodes hosts)
fleet_job_dur = min(spec.exec_sec, float(nominal_fleet_exec_sec))
unjittered_fleet_peak = spec.fleet_nodes * single_cron_peak
if spec.jitter_sec <= 0.0:
systemd_fleet_peak = spec.fleet_nodes * single_flock_peak
expected_fleet_concurrency = float(spec.fleet_nodes)
else:
offsets = [(i + 0.5) / spec.fleet_nodes * spec.jitter_sec for i in range(spec.fleet_nodes)]
grid_max = max(spec.jitter_sec + fleet_job_dur, 60.0)
steps = int(grid_max * 4) + 1
systemd_fleet_peak = 0
for step_idx in range(steps):
t_val = step_idx * 0.25
active_here = sum(1 for off in offsets if off <= t_val < off + fleet_job_dur)
if active_here > systemd_fleet_peak:
systemd_fleet_peak = active_here
expected_fleet_concurrency = spec.fleet_nodes * fleet_job_dur / spec.jitter_sec
peak_reduction_pct = (
100.0 * (1.0 - (systemd_fleet_peak / float(unjittered_fleet_peak)))
if unjittered_fleet_peak > 0
else 0.0
)
return {
"utilization_rho": round(rho, 4),
"single_node_cron_peak": int(single_cron_peak),
"single_node_flock_peak": int(single_flock_peak),
"flock_ticks_skipped": int(flock_skipped),
"fleet_job_duration_sec": round(fleet_job_dur, 2),
"unjittered_nominal_herd_peak": int(spec.fleet_nodes),
"unjittered_fleet_peak": int(unjittered_fleet_peak),
"systemd_jitter_fleet_peak": int(systemd_fleet_peak),
"littles_law_expected_concurrency": round(expected_fleet_concurrency, 2),
"fleet_peak_reduction_pct": round(peak_reduction_pct, 2),
}
def _merge_intervals_duration(intervals: list[tuple[float, float]], window_sec: float) -> float:
clipped: list[tuple[float, float]] = []
for start, end in intervals:
s = max(0.0, min(window_sec, float(start)))
e = max(0.0, min(window_sec, float(end)))
if e > s:
clipped.append((s, e))
if not clipped:
return 0.0
clipped.sort()
merged: list[tuple[float, float]] = [clipped[0]]
for s, e in clipped[1:]:
prev_s, prev_e = merged[-1]
if s <= prev_e:
merged[-1] = (prev_s, max(prev_e, e))
else:
merged.append((s, e))
return sum(e - s for s, e in merged)
def compute_psi_pressure(
some_intervals: list[tuple[float, float]],
full_intervals: list[tuple[float, float]],
window_sec: float = 10.0,
) -> dict[str, Any]:
"""Compute cgroups v2 Pressure Stall Information (PSI) some/full percentages & total_us."""
if window_sec <= 0.0:
raise ValueError("window_sec must be > 0.")
some_sec = _merge_intervals_duration(some_intervals, window_sec)
full_sec = _merge_intervals_duration(full_intervals, window_sec)
some_pct = 100.0 * some_sec / window_sec
full_pct = 100.0 * full_sec / window_sec
return {
"window_sec": float(window_sec),
"some_pct": round(some_pct, 2),
"full_pct": round(full_pct, 2),
"some_total_us": round(some_sec * 1_000_000),
"full_total_us": round(full_sec * 1_000_000),
"oomd_thrashing_risk": full_pct >= 10.0,
}
"""Offline-safe CLI website text crawler, redirect SSRF guard, SHA-256 dedup & POSIX atomic writes."""
from __future__ import annotations
import argparse
import hashlib
import ipaddress
import json
import os
import posixpath
import signal
import socket
import sys
import tempfile
import threading
import time
from collections import deque
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import asdict, dataclass
from html.parser import HTMLParser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qsl, urlencode, urljoin, urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
FIXTURE_PAGES: dict[str, tuple[int, str] | tuple[int, str, dict[str, str]]] = {
"/": (
200,
"""<!doctype html>
<html><head><title>FSDS Linux Knowledge Hub</title></head>
<body>
<header><script>window.__ignored = "not visible";</script></header>
<h1>GNU/Linux Engineering Curriculum</h1>
<p>Core foundations covering VFS inodes, POSIX permissions, Bash strict mode, Makefile DAGs, and systemd timers.</p>
<nav>
<a href="/docs/linux">Linux VFS & Inodes</a>
<a href="/docs/bash">Production Bash Scripting</a>
<a href="/docs/makefile">Makefile DAG & Compilation</a>
<a href="/docs/systemd">systemd Timers, cgroups v2 & eBPF</a>
<a href="/docs/linux?utm_source=cron#inode">Tracked Duplicate Link</a>
<a href="/missing-404">Broken Page</a>
<a href="https://evil-example.com/exfiltrate">External Off-Domain Link</a>
<a href="http://169.254.169.254/latest/meta-data/">Cloud Metadata SSRF Link</a>
</nav>
</body></html>""",
),
"/docs/linux": (
200,
"""<!doctype html>
<html><head><title>Linux VFS, Inodes & POSIX Permissions</title></head>
<body>
<h2>Virtual File System & Reference Counting</h2>
<p>Data blocks are reclaimed only when i_nlink equals zero and open_fd_refs equals zero. Use lsof +L1 to find unlinked logs.</p>
<a href="/docs/inode-leak">50 GiB Deleted Log Case</a>
<a href="/docs/permissions">umask 0027 & Sticky Bit</a>
</body></html>""",
),
"/docs/inode-leak": (
200,
"""<!doctype html>
<html><head><title>50 GiB Deleted Log Open-FD Case</title></head>
<body>
<p>When rm removes a directory entry while a daemon holds fd=3 open, df reports 100% full while du reports near zero. Truncate /proc/pid/fd/3 safely.</p>
</body></html>""",
),
"/docs/permissions": (
200,
"""<!doctype html>
<html><head><title>POSIX Modes & umask Algebra</title></head>
<body>
<p>Effective creation mode equals base_mode bitwise-AND bitwise-NOT umask. Sticky bit 1777 prevents non-owners from unlinking files in /tmp.</p>
<a href="/docs/mirror">Mirrored Duplicate Text</a>
</body></html>""",
),
"/docs/mirror": (
200,
"""<!doctype html>
<html><head><title>Mirrored Inode Article</title></head>
<body>
<p>When rm removes a directory entry while a daemon holds fd=3 open, df reports 100% full while du reports near zero. Truncate /proc/pid/fd/3 safely.</p>
</body></html>""",
),
"/docs/bash": (
200,
"""<!doctype html>
<html><head><title>Production Bash Strict Mode & flock</title></head>
<body>
<p>Start scripts with set -Eeuo pipefail, IFS, trap cleanup EXIT INT TERM, mktemp -d, flock -n, and left-to-right redirection > out.log 2>&1.</p>
</body></html>""",
),
"/docs/makefile": (
200,
"""<!doctype html>
<html><head><title>Compilation Toolchain & Makefile DAG</title></head>
<body>
<p>Four C stages: preprocess, compile, assemble, link. Always include .DELETE_ON_ERROR and .PHONY so crashed recipes never poison future make runs.</p>
</body></html>""",
),
"/docs/systemd": (
200,
"""<!doctype html>
<html><head><title>systemd Timers, cgroups v2 PSI & eBPF</title></head>
<body>
<p>Replace legacy cron with systemd timers using RandomizedDelaySec, Persistent=true, cgroups v2 MemoryMax, PSI stalls, and low-overhead eBPF tracing.</p>
</body></html>""",
),
}
_TRACKING_QUERY_PREFIXES = ("utm_",)
_TRACKING_QUERY_KEYS = frozenset({"fbclid", "gclid", "mc_cid", "mc_eid"})
_METADATA_HOSTS = frozenset({"169.254.169.254", "metadata.google.internal", "metadata.azure.internal"})
_LOCAL_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost"})
class SSRFBlockedError(PermissionError, URLError):
"""Raised when a URL or HTTP redirect violates scheme, allowlist, or SSRF IP policy."""
def __init__(self, reason: str, target_url: str = "") -> None:
PermissionError.__init__(self, reason)
self.reason = reason
self.target_url = target_url
def __str__(self) -> str:
return str(self.reason)
class _TextAndLinkParser(HTMLParser):
"""Extract clean visible text, title and href links while ignoring script/style tags."""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self._skip_depth = 0
self._in_title = False
self.title_chunks: list[str] = []
self.text_chunks: list[str] = []
self.links: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
lower = tag.lower()
if lower in {"script", "style", "noscript"}:
self._skip_depth += 1
elif lower == "title":
self._in_title = True
elif lower == "a":
for k, v in attrs:
if k.lower() == "href" and v:
self.links.append(v.strip())
def handle_endtag(self, tag: str) -> None:
lower = tag.lower()
if lower in {"script", "style", "noscript"} and self._skip_depth > 0:
self._skip_depth -= 1
elif lower == "title":
self._in_title = False
def handle_data(self, data: str) -> None:
if self._skip_depth > 0:
return
cleaned = " ".join(data.split())
if not cleaned:
return
if self._in_title:
self.title_chunks.append(cleaned)
else:
self.text_chunks.append(cleaned)
def extract_html_text_and_links(html_text: str, base_url: str) -> tuple[str, str, list[str]]:
"""Parse HTML into (title, visible_text, resolved_links)."""
parser = _TextAndLinkParser()
parser.feed(html_text)
parser.close()
title = " ".join(parser.title_chunks).strip()
visible_text = " ".join(parser.text_chunks).strip()
resolved = [urljoin(base_url, href) for href in parser.links]
return title, visible_text, resolved
def canonicalize_url(raw_url: str, drop_tracking_params: bool = True) -> str:
"""Normalize URL according to RFC 3986 while rejecting non-HTTP schemes and userinfo."""
parts = urlsplit(raw_url.strip())
scheme = parts.scheme.lower()
if scheme not in {"http", "https"}:
raise ValueError(f"Disallowed URL scheme {scheme!r}: only http/https are allowed.")
if parts.username is not None or parts.password is not None:
raise ValueError("URLs containing userinfo (user:pass@host) are forbidden.")
if not parts.hostname:
raise ValueError(f"URL is missing a hostname: {raw_url!r}")
host = parts.hostname.lower().rstrip(".")
port = parts.port
if (scheme == "http" and port == 80) or (scheme == "https" and port == 443) or port is None:
netloc = f"[{host}]" if ":" in host else host
else:
netloc = f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
raw_path = parts.path or "/"
had_trailing_slash = raw_path.endswith("/") and raw_path != "/"
norm_path = posixpath.normpath(raw_path)
if not norm_path.startswith("/"):
norm_path = "/" + norm_path
if had_trailing_slash and not norm_path.endswith("/"):
norm_path += "/"
query_pairs = parse_qsl(parts.query, keep_blank_values=False)
if drop_tracking_params:
query_pairs = [
(k, v)
for (k, v) in query_pairs
if not k.lower().startswith(_TRACKING_QUERY_PREFIXES) and k.lower() not in _TRACKING_QUERY_KEYS
]
query_pairs.sort()
query_str = urlencode(query_pairs)
return urlunsplit((scheme, netloc, norm_path, query_str, ""))
def _is_blocked_ip(
ip_obj: ipaddress.IPv4Address | ipaddress.IPv6Address,
*,
allow_loopback_test: bool = False,
) -> bool:
"""Return True if IP is private, link-local, reserved, multicast, unspecified, or unallowed loopback."""
if isinstance(ip_obj, ipaddress.IPv6Address) and ip_obj.ipv4_mapped is not None:
ip_obj = ip_obj.ipv4_mapped
if ip_obj.is_loopback:
return not allow_loopback_test
return bool(
ip_obj.is_private
or ip_obj.is_link_local
or ip_obj.is_reserved
or ip_obj.is_multicast
or ip_obj.is_unspecified
or not ip_obj.is_global
)
def validate_target_url(
raw_url: str,
allowed_hosts: tuple[str, ...] = (),
*,
allow_loopback_test: bool = False,
resolve_dns: bool = True,
) -> tuple[bool, str]:
"""Validate URL scheme, optional host allowlist, literal IP, and post-DNS resolved IP against SSRF."""
try:
canon = canonicalize_url(raw_url)
except ValueError as exc:
return False, f"invalid_url:{exc}"
parts = urlsplit(canon)
scheme = parts.scheme.lower()
host = (parts.hostname or "").lower().rstrip(".")
if not host:
return False, "invalid_url:missing_host"
if host in _METADATA_HOSTS:
return False, f"ssrf_blocked_metadata_host:{host}"
normalized_allow = tuple(h.strip().lower().rstrip(".") for h in allowed_hosts if h.strip())
if normalized_allow and not any(host == dom or host.endswith(f".{dom}") for dom in normalized_allow):
return False, f"domain_not_allowlisted:{host}"
# 1. Check literal IP host before DNS
try:
ip_literal = ipaddress.ip_address(host)
except ValueError:
ip_literal = None
if ip_literal is not None:
if _is_blocked_ip(ip_literal, allow_loopback_test=allow_loopback_test):
return False, f"ssrf_blocked_ip:{host}"
return True, "allowed"
# 2. Check post-DNS resolved IP(s) via socket.getaddrinfo
if resolve_dns:
port = parts.port or (443 if scheme == "https" else 80)
try:
addr_infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
except OSError as exc:
return False, f"dns_resolution_failed:{host}:{exc}"
if not addr_infos:
return False, f"dns_resolution_empty:{host}"
for info in addr_infos:
raw_addr = info[4][0]
# Strip IPv6 zone scope if present (e.g. fe80::1%eth0)
addr_no_zone = str(raw_addr).split("%", 1)[0]
try:
resolved_ip = ipaddress.ip_address(addr_no_zone)
except ValueError:
return False, f"dns_invalid_ip:{raw_addr}"
if _is_blocked_ip(resolved_ip, allow_loopback_test=allow_loopback_test):
return False, f"ssrf_blocked_resolved_ip:{addr_no_zone}"
return True, "allowed"
def is_url_allowed(url: str, allowed_hosts: tuple[str, ...]) -> tuple[bool, str]:
"""Enforce strict domain allowlist and SSRF boundary against IP/metadata/substring bypasses."""
normalized_allow = tuple(h.strip().lower().rstrip(".") for h in allowed_hosts if h.strip())
if not normalized_allow:
return False, "empty_allowlist"
try:
canon = canonicalize_url(url)
except ValueError as exc:
return False, f"invalid_url:{exc}"
host = (urlsplit(canon).hostname or "").lower().rstrip(".")
explicitly_allowlisted_local = host in normalized_allow and host in _LOCAL_LOOPBACK_HOSTS
return validate_target_url(
canon,
normalized_allow,
allow_loopback_test=explicitly_allowlisted_local,
resolve_dns=False,
)
class SafeHTTPRedirectHandler(HTTPRedirectHandler):
"""HTTPRedirectHandler enforcing scheme, allowlist & post-DNS SSRF checks on EVERY redirect hop."""
def __init__(
self,
allowed_hosts: tuple[str, ...] = (),
*,
allow_loopback_test: bool = False,
resolve_dns: bool = True,
) -> None:
self.allowed_hosts = tuple(allowed_hosts)
self.allow_loopback_test = allow_loopback_test
self.resolve_dns = resolve_dns
def _assert_safe_redirect_target(self, target_url: str) -> None:
ok, reason = validate_target_url(
target_url,
self.allowed_hosts,
allow_loopback_test=self.allow_loopback_test,
resolve_dns=self.resolve_dns,
)
if not ok:
raise SSRFBlockedError(
f"Redirect SSRF/policy blocked ({reason}): {target_url}",
target_url=target_url,
)
def http_error_302(self, req: Request, fp: Any, code: int, msg: str, headers: Any) -> Any:
location = headers.get("location") or headers.get("uri")
if location:
target_url = urljoin(req.full_url, location.strip())
try:
self._assert_safe_redirect_target(target_url)
except SSRFBlockedError:
fp.close()
raise
return super().http_error_302(req, fp, code, msg, headers)
http_error_301 = http_error_303 = http_error_307 = http_error_308 = http_error_302
def redirect_request(
self,
req: Request,
fp: Any,
code: int,
msg: str,
headers: Any,
newurl: str,
) -> Request | None:
self._assert_safe_redirect_target(newurl)
return super().redirect_request(req, fp, code, msg, headers, newurl)
def atomic_write_text(target_path: Path | str, content: str) -> None:
"""Crash-safe POSIX atomic write: stage in same dir -> flush -> fsync -> os.replace."""
dest = Path(target_path)
dest.parent.mkdir(parents=True, exist_ok=True)
fd, tmp_name = tempfile.mkstemp(prefix=f".{dest.name}.", suffix=".tmp", dir=str(dest.parent))
tmp_path = Path(tmp_name)
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh:
fh.write(content)
fh.flush()
os.fsync(fh.fileno())
os.replace(tmp_path, dest)
except BaseException:
if tmp_path.exists():
tmp_path.unlink(missing_ok=True)
raise
def atomic_write_jsonl(target_path: Path | str, records: list[dict[str, Any]]) -> None:
lines = "".join(json.dumps(rec, ensure_ascii=False, sort_keys=True) + "\n" for rec in records)
atomic_write_text(target_path, lines)
def atomic_write_json(target_path: Path | str, payload: dict[str, Any]) -> None:
text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
atomic_write_text(target_path, text)
@dataclass(frozen=True, slots=True)
class CrawledDocument:
url: str
depth: int
status_code: int
title: str
word_count: int
sha256: str
text: str
@dataclass(frozen=True, slots=True)
class CrawlReport:
seed_url: str
allowed_hosts: tuple[str, ...]
urls_visited: int
unique_documents: int
content_dedup_skipped: int
url_dedup_skipped: int
ssrf_or_domain_blocked: int
http_errors: int
blocked_targets: tuple[str, ...]
documents: tuple[CrawledDocument, ...]
interrupted: bool = False
@contextmanager
def LocalFixtureServer(
pages: dict[str, tuple[int, str] | tuple[int, str, dict[str, str]]] | None = None,
) -> Iterator[str]:
"""Ephemeral 127.0.0.1 HTTP server serving deterministic HTML/redirect pages for offline labs."""
corpus = pages if pages is not None else FIXTURE_PAGES
class _FixtureHandler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
path_only = urlsplit(self.path).path or "/"
entry = corpus.get(path_only, (404, "<html><title>Not Found</title><body>404</body></html>"))
if len(entry) == 3:
status, body, extra_headers = entry
else:
status, body = entry
extra_headers = {}
payload = body.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
for hdr_name, hdr_val in extra_headers.items():
self.send_header(hdr_name, hdr_val)
self.end_headers()
self.wfile.write(payload)
def log_message(self, format: str, *args: Any) -> None:
return
server = ThreadingHTTPServer(("127.0.0.1", 0), _FixtureHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
host, port = server.server_address[:2]
host_str = host.decode("ascii") if isinstance(host, bytes) else str(host)
yield f"http://{host_str}:{port}/"
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2.0)
def install_signal_handlers(
stop_event: threading.Event,
) -> tuple[dict[int, Any], dict[str, int | None]]:
"""Register SIGTERM/SIGINT graceful shutdown handlers on the main thread."""
previous: dict[int, Any] = {}
state: dict[str, int | None] = {"signum": None}
def _handle(signum: int, _frame: Any) -> None:
state["signum"] = signum
stop_event.set()
for sig_name in ("SIGINT", "SIGTERM"):
sig = getattr(signal, sig_name, None)
if sig is None:
continue
try:
previous[int(sig)] = signal.getsignal(sig)
signal.signal(sig, _handle)
except ValueError:
# signal.signal only works on the main thread of the main interpreter
pass
return previous, state
def restore_signal_handlers(previous: dict[int, Any]) -> None:
"""Restore previously registered signal handlers."""
for sig_num, handler in previous.items():
try:
signal.signal(sig_num, handler)
except (ValueError, OSError):
pass
def check_crawler_health(
*,
output_dir: Path | str | None = None,
stop_event: threading.Event | None = None,
probe_fixture: bool = False,
) -> dict[str, Any]:
"""Readiness and liveness probe verifying shutdown flag, writable output dir & optional fixture fetch."""
shutting_down = bool(stop_event is not None and stop_event.is_set())
dir_writable = True
if output_dir is not None:
target_dir = Path(output_dir)
try:
target_dir.mkdir(parents=True, exist_ok=True)
fd, probe_path = tempfile.mkstemp(prefix=".health.", suffix=".tmp", dir=str(target_dir))
os.close(fd)
Path(probe_path).unlink(missing_ok=True)
except OSError:
dir_writable = False
fixture_ok: bool | None = None
if probe_fixture and not shutting_down:
try:
with LocalFixtureServer() as base_url:
opener = build_opener(
SafeHTTPRedirectHandler(("127.0.0.1",), allow_loopback_test=True, resolve_dns=True)
)
with opener.open(Request(base_url, headers={"User-Agent": "fsds-health/0.1"}), timeout=2.0) as resp:
fixture_ok = int(getattr(resp, "status", 0)) == 200
except OSError:
fixture_ok = False
ready = (not shutting_down) and dir_writable and (fixture_ok is not False)
status = "draining" if shutting_down else ("ready" if ready else "unhealthy")
return {
"status": status,
"ready": ready,
"shutting_down": shutting_down,
"output_dir_writable": dir_writable,
"fixture_probe_ok": fixture_ok,
"timestamp_epoch": round(time.time(), 3),
}
def crawl_site(
seed_url: str,
allowed_hosts: tuple[str, ...],
max_pages: int = 10,
max_depth: int = 3,
timeout_sec: float = 3.0,
*,
allow_loopback_test: bool | None = None,
resolve_dns: bool = True,
stop_event: threading.Event | None = None,
) -> CrawlReport:
"""BFS crawl starting at seed_url with RFC 3986 normalization, redirect SSRF guard & SHA-256 dedup."""
seed_canon = canonicalize_url(seed_url)
normalized_allow = tuple(h.strip().lower().rstrip(".") for h in allowed_hosts if h.strip())
if not normalized_allow:
raise PermissionError(f"Seed URL rejected (empty_allowlist): {seed_url}")
effective_loopback = (
any(h in _LOCAL_LOOPBACK_HOSTS for h in normalized_allow)
if allow_loopback_test is None
else allow_loopback_test
)
ok_seed, reason = validate_target_url(
seed_canon,
normalized_allow,
allow_loopback_test=effective_loopback,
resolve_dns=resolve_dns,
)
if not ok_seed:
raise SSRFBlockedError(f"Seed URL rejected ({reason}): {seed_url}", target_url=seed_url)
opener = build_opener(
SafeHTTPRedirectHandler(
normalized_allow,
allow_loopback_test=effective_loopback,
resolve_dns=resolve_dns,
)
)
queue: deque[tuple[str, int]] = deque([(seed_canon, 0)])
queued_or_visited: set[str] = {seed_canon}
seen_sha256: set[str] = set()
docs: list[CrawledDocument] = []
blocked: list[str] = []
urls_visited = 0
content_dedup_skipped = 0
url_dedup_skipped = 0
http_errors = 0
interrupted = False
while queue and urls_visited < max_pages:
if stop_event is not None and stop_event.is_set():
interrupted = True
break
curr_url, depth = queue.popleft()
ok_curr, reason_curr = validate_target_url(
curr_url,
normalized_allow,
allow_loopback_test=effective_loopback,
resolve_dns=resolve_dns,
)
if not ok_curr:
blocked.append(curr_url)
if curr_url == seed_canon:
raise SSRFBlockedError(f"Seed URL rejected ({reason_curr}): {curr_url}", target_url=curr_url)
continue
urls_visited += 1
req = Request(curr_url, headers={"User-Agent": "fsds-sota-crawler/0.1"})
try:
with opener.open(req, timeout=timeout_sec) as resp:
status_code = int(getattr(resp, "status", 200))
final_url = str(resp.geturl() or curr_url)
ok_final, reason_final = validate_target_url(
final_url,
normalized_allow,
allow_loopback_test=effective_loopback,
resolve_dns=resolve_dns,
)
if not ok_final:
raise SSRFBlockedError(
f"Final target rejected ({reason_final}): {final_url}",
target_url=final_url,
)
raw_bytes = resp.read(1_048_576)
except SSRFBlockedError as exc:
blocked.append(exc.target_url or curr_url)
if curr_url == seed_canon:
raise
continue
except HTTPError as exc:
http_errors += 1
if curr_url == seed_canon:
raise RuntimeError(f"Seed URL HTTP failure {exc.code}: {curr_url}") from exc
continue
except URLError as exc:
http_errors += 1
if curr_url == seed_canon:
raise RuntimeError(f"Seed URL network failure: {exc.reason}") from exc
continue
html_text = raw_bytes.decode("utf-8", errors="replace")
title, visible_text, links = extract_html_text_and_links(html_text, final_url)
digest = hashlib.sha256(visible_text.encode("utf-8")).hexdigest()
if digest in seen_sha256:
content_dedup_skipped += 1
else:
seen_sha256.add(digest)
docs.append(
CrawledDocument(
url=final_url,
depth=depth,
status_code=status_code,
title=title,
word_count=len(visible_text.split()),
sha256=digest,
text=visible_text,
)
)
if depth < max_depth:
for raw_link in links:
allowed, _ = validate_target_url(
raw_link,
normalized_allow,
allow_loopback_test=effective_loopback,
resolve_dns=False,
)
if not allowed:
blocked.append(raw_link)
continue
canon_link = canonicalize_url(raw_link)
if canon_link in queued_or_visited:
url_dedup_skipped += 1
continue
queued_or_visited.add(canon_link)
queue.append((canon_link, depth + 1))
return CrawlReport(
seed_url=seed_canon,
allowed_hosts=tuple(allowed_hosts),
urls_visited=urls_visited,
unique_documents=len(docs),
content_dedup_skipped=content_dedup_skipped,
url_dedup_skipped=url_dedup_skipped,
ssrf_or_domain_blocked=len(blocked),
http_errors=http_errors,
blocked_targets=tuple(blocked),
documents=tuple(docs),
interrupted=interrupted,
)
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="FSDS-SOTA-2026 Offline-Safe CLI Website Text Crawler")
parser.add_argument("--seed-url", type=str, default=None, help="Seed HTTP/HTTPS URL to crawl.")
parser.add_argument(
"--allow-host",
action="append",
dest="allow_hosts",
default=[],
help="Allowed host/domain (repeatable).",
)
parser.add_argument("--serve-fixtures", action="store_true", help="Launch local 127.0.0.1 fixture server.")
parser.add_argument("--max-pages", type=int, default=10, help="Maximum pages to fetch.")
parser.add_argument("--max-depth", type=int, default=3, help="Maximum BFS link depth.")
parser.add_argument("--output-jsonl", type=str, default=None, help="Atomic JSONL output path.")
parser.add_argument("--output-raw", type=str, default=None, help="Atomic raw crawl snapshot JSON path.")
parser.add_argument("--report-json", type=str, default=None, help="Atomic crawl summary JSON path.")
parser.add_argument("--fail-on-http-error", action="store_true", help="Exit 3 if any non-seed page returns 4xx/5xx.")
parser.add_argument("--healthcheck", action="store_true", help="Run readiness probe and exit 0/3.")
return parser
def main(argv: list[str] | None = None) -> int:
parser = _build_parser()
args = parser.parse_args(argv)
stop_event = threading.Event()
prev_handlers, sig_state = install_signal_handlers(stop_event)
try:
if args.healthcheck:
out_dir = Path(args.output_jsonl).parent if args.output_jsonl else None
health = check_crawler_health(output_dir=out_dir, stop_event=stop_event, probe_fixture=True)
print(json.dumps(health, ensure_ascii=False))
return 0 if health["ready"] else 3
if args.max_pages <= 0 or args.max_depth < 0:
print("Validation error: --max-pages must be > 0 and --max-depth >= 0.", file=sys.stderr)
return 2
if not args.serve_fixtures and not args.seed_url:
print("Validation error: pass --serve-fixtures or --seed-url.", file=sys.stderr)
return 2
try:
if args.serve_fixtures:
with LocalFixtureServer() as base_url:
hosts = tuple(args.allow_hosts) if args.allow_hosts else ("127.0.0.1",)
report = crawl_site(
seed_url=base_url,
allowed_hosts=hosts,
max_pages=args.max_pages,
max_depth=args.max_depth,
stop_event=stop_event,
)
else:
seed_canon = canonicalize_url(args.seed_url)
seed_host = urlsplit(seed_canon).hostname or ""
hosts = tuple(args.allow_hosts) if args.allow_hosts else (seed_host,)
report = crawl_site(
seed_url=seed_canon,
allowed_hosts=hosts,
max_pages=args.max_pages,
max_depth=args.max_depth,
stop_event=stop_event,
)
except (ValueError, PermissionError) as exc:
print(f"Policy/Validation error: {exc}", file=sys.stderr)
return 2
except (RuntimeError, OSError) as exc:
print(f"Upstream/IO failure: {exc}", file=sys.stderr)
return 3
doc_dicts = [asdict(d) for d in report.documents]
summary = {
"seed_url": report.seed_url,
"allowed_hosts": list(report.allowed_hosts),
"urls_visited": report.urls_visited,
"unique_documents": report.unique_documents,
"content_dedup_skipped": report.content_dedup_skipped,
"url_dedup_skipped": report.url_dedup_skipped,
"ssrf_or_domain_blocked": report.ssrf_or_domain_blocked,
"http_errors": report.http_errors,
"blocked_targets": list(report.blocked_targets),
"interrupted": report.interrupted,
}
try:
if args.output_jsonl:
atomic_write_jsonl(args.output_jsonl, doc_dicts)
if args.output_raw:
atomic_write_json(args.output_raw, {"summary": summary, "documents": doc_dicts})
if args.report_json:
atomic_write_json(args.report_json, summary)
except OSError as exc:
print(f"Atomic persistence error: {exc}", file=sys.stderr)
return 3
if report.interrupted and sig_state["signum"] is not None:
return 128 + sig_state["signum"]
if args.fail_on_http_error and report.http_errors > 0:
print(f"Upstream HTTP errors encountered: {report.http_errors}", file=sys.stderr)
return 3
print(
f"[CLI-CRAWLER] visited={report.urls_visited} unique_docs={report.unique_documents} "
f"sha256_dedup={report.content_dedup_skipped} url_dedup={report.url_dedup_skipped} "
f"blocked={report.ssrf_or_domain_blocked} http_errors={report.http_errors}"
)
return 0
finally:
restore_signal_handlers(prev_handlers)
if __name__ == "__main__":
raise SystemExit(main())
"""End-to-end CLI workbench for FSDS-SOTA-2026 Track 2 Unit T2-P1-U01 (Lab 01)."""
from __future__ import annotations
import argparse
import json
import sys
import tempfile
from dataclasses import asdict
from pathlib import Path
from urllib.parse import urlsplit
_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 linux_crawler_lab.cli_crawler import ( # noqa: E402
LocalFixtureServer,
atomic_write_jsonl,
crawl_site,
)
from linux_crawler_lab.posix_and_make_engine import ( # noqa: E402
VirtualFileSystem,
check_directory_access,
compute_psi_pressure,
parse_cron_expression,
parse_makefile,
plan_makefile_rebuild,
resolve_posix_permissions,
simulate_cron_vs_systemd_fleet,
simulate_fd_redirection,
)
GIB = 1024**3
def run_demo_suite(quick: bool = False) -> dict:
# ------------------------------------------------------------------
# [1] POSIX Permissions, umask & VFS 50 GiB Deleted-Log Simulation
# ------------------------------------------------------------------
perm_file = resolve_posix_permissions(0o666, 0o022, is_dir=False)
perm_dir = resolve_posix_permissions(0o777, 0o027, is_dir=True)
perm_sticky = resolve_posix_permissions(0o777, 0o000, is_dir=True, special_bits=0o1000)
sticky_other_blocked = not check_directory_access(
dir_mode=0o1777, op="unlink", dir_uid=0, file_uid=1001, caller_uid=1002, caller_class="other"
)
sticky_owner_ok = check_directory_access(
dir_mode=0o1777, op="unlink", dir_uid=0, file_uid=1001, caller_uid=1001, caller_class="other"
)
vfs = VirtualFileSystem()
log_path = "/var/log/crawler/payloads.log"
vfs.create_file(log_path, size_bytes=0)
fd3 = vfs.open_fd(pid=18422, path=log_path, o_append=True)
vfs.write_fd(pid=18422, fd=fd3, num_bytes=50 * GIB)
df_before_rm = vfs.df_used_bytes() / GIB
du_before_rm = vfs.du_apparent_bytes() / GIB
unlink_info = vfs.unlink(log_path)
df_after_rm = vfs.df_used_bytes() / GIB
du_after_rm = vfs.du_apparent_bytes() / GIB
lsof_rows = vfs.lsof_deleted_open()
trunc_info = vfs.truncate_proc_fd(pid=18422, fd=fd3)
df_after_trunc = vfs.df_used_bytes() / GIB
reclaimed_on_close = vfs.close_fd(pid=18422, fd=fd3)
# ------------------------------------------------------------------
# [2] FD dup2 Ordering & Real Makefile DAG + .DELETE_ON_ERROR Audit
# ------------------------------------------------------------------
fd_correct = simulate_fd_redirection([">out.log", "2>&1"])
fd_bugged = simulate_fd_redirection(["2>&1", ">out.log"])
fd_clobber = simulate_fd_redirection([">out.log", "2>out.log"])
makefile_path = _LAB_ROOT / "Makefile"
parsed_mk = parse_makefile(makefile_path.read_text(encoding="utf-8"))
rules = parsed_mk["rules"]
weights = {
"data/raw_pages.json": 4.0,
"data/corpus.jsonl": 2.0,
"artifacts/posix_audit.json": 5.0,
"artifacts/crawl_report.json": 1.0,
}
clean_mtimes: dict[str, float | None] = {
"src/linux_crawler_lab/cli_crawler.py": 100.0,
"src/linux_crawler_lab/posix_and_make_engine.py": 100.0,
}
plan_j1 = plan_makefile_rebuild(rules, clean_mtimes, goal="all", jobs=1, work_estimates=weights)
plan_j2 = plan_makefile_rebuild(rules, clean_mtimes, goal="all", jobs=2, work_estimates=weights)
# Incremental rebuild after touching ONLY posix_and_make_engine.py
inc_mtimes = dict(plan_j2["updated_mtimes"])
inc_mtimes["src/linux_crawler_lab/posix_and_make_engine.py"] = 5000.0
plan_inc = plan_makefile_rebuild(rules, inc_mtimes, goal="all", jobs=2, work_estimates=weights)
inc_rebuilt_files = [t for t in plan_inc["rebuilt_targets"] if t in rules and not rules[t].is_phony]
# Crash on data/corpus.jsonl without vs with .DELETE_ON_ERROR
crash_no_del = plan_makefile_rebuild(
rules,
clean_mtimes,
goal="all",
jobs=1,
work_estimates=weights,
failed_target="data/corpus.jsonl",
delete_on_error=False,
failure_timestamp=8000.0,
)
followup_poisoned = plan_makefile_rebuild(
rules, crash_no_del["updated_mtimes"], goal="all", jobs=1, work_estimates=weights
)
crash_with_del = plan_makefile_rebuild(
rules,
clean_mtimes,
goal="all",
jobs=1,
work_estimates=weights,
failed_target="data/corpus.jsonl",
delete_on_error=True,
failure_timestamp=8000.0,
)
followup_repaired = plan_makefile_rebuild(
rules, crash_with_del["updated_mtimes"], goal="all", jobs=1, work_estimates=weights
)
# ------------------------------------------------------------------
# [3] Cron Overlap vs flock + systemd Jitter & cgroups v2 PSI
# ------------------------------------------------------------------
cron_quirk = parse_cron_expression("0 9 13 * 5")
sched_sim = simulate_cron_vs_systemd_fleet(
period_sec=60.0,
exec_sec=150.0,
fleet_nodes=100,
jitter_sec=45.0,
horizon_sec=300.0,
)
psi_healthy = compute_psi_pressure([(0.2, 0.45)], [], window_sec=10.0)
psi_thrash = compute_psi_pressure(
[(0.5, 2.34)],
[(0.8, 1.45), (3.0, 3.60)],
window_sec=10.0,
)
# ------------------------------------------------------------------
# [4] Offline Ephemeral HTTP CLI Crawler & Atomic JSONL Persistence
# ------------------------------------------------------------------
with LocalFixtureServer() as base_url:
crawl_res = crawl_site(
seed_url=base_url,
allowed_hosts=("127.0.0.1",),
max_pages=12,
max_depth=3,
)
with tempfile.TemporaryDirectory() as tmp_dir:
jsonl_tmp_target = Path(tmp_dir) / "corpus.jsonl"
atomic_write_jsonl(jsonl_tmp_target, [asdict(d) for d in crawl_res.documents])
atomic_jsonl_bytes = jsonl_tmp_target.stat().st_size
atomic_jsonl_lines = len(jsonl_tmp_target.read_text(encoding="utf-8").splitlines())
workbench_panels = {
"kpis": [
{
"id": "kpi_posix_umask_and_sticky",
"label": "POSIX umask 0027 & Sticky Guard",
"value": f"{perm_dir['octal_str']} ({perm_dir['ls_string']})",
"unit": "mode",
"status": "ok",
"detail": f"0666&~0022={perm_file['octal_str']} ({perm_file['ls_string']}); 1777 sticky blocks non-owner={sticky_other_blocked}.",
},
{
"id": "kpi_vfs_deleted_log_leak",
"label": "50 GiB Deleted Log (df vs du)",
"value": f"{df_after_rm:.1f} vs {du_after_rm:.1f}",
"unit": "GiB",
"status": "critical",
"detail": f"After rm: i_nlink={unlink_info['nlink']}, open_fd={unlink_info['open_fd_count']} -> lsof +L1=1; proc truncate -> {df_after_trunc:.1f} GiB.",
},
{
"id": "kpi_fd_dup2_redirection",
"label": "FD 0/1/2 Order (>log 2>&1 vs 2>&1 >log)",
"value": f"{fd_correct['fd_2_target']} vs {fd_bugged['fd_2_target']}",
"unit": "fd[2]",
"status": "warn",
"detail": f"2>&1 >out.log leaks stderr to TTY (shared_desc={fd_bugged['shared_open_file_description']}); >out.log 2>&1 shares struct file.",
},
{
"id": "kpi_makefile_dag_parallel",
"label": "Makefile DAG (-j2 vs -j1 & Incremental)",
"value": f"{plan_j2['rebuilt_tp']:.1f}s ({plan_j2['parallel_speedup']:.2f}x)",
"unit": "T_inf=7.0s",
"status": "ok",
"detail": f"T1={plan_j1['full_dag_t1']:.1f}s -> -j2={plan_j2['rebuilt_tp']:.1f}s; incremental touch rebuilds {len(inc_rebuilt_files)}/4 file targets; .DELETE_ON_ERROR repairs crash.",
},
{
"id": "kpi_cron_vs_systemd_fleet",
"label": "100-Node Fleet Peak (Cron vs systemd Jitter)",
"value": f"{sched_sim['unjittered_fleet_peak']} -> {sched_sim['systemd_jitter_fleet_peak']}",
"unit": f"-{sched_sim['fleet_peak_reduction_pct']:.1f}%",
"status": "ok",
"detail": f"Unprotected single-node overlap={sched_sim['single_node_cron_peak']} vs flock={sched_sim['single_node_flock_peak']}; Little's Law E[C]={sched_sim['littles_law_expected_concurrency']}.",
},
{
"id": "kpi_offline_cli_crawler",
"label": "Offline CLI Crawler (Visited / Unique / Blocked)",
"value": f"{crawl_res.urls_visited} -> {crawl_res.unique_documents} docs",
"unit": f"blk={crawl_res.ssrf_or_domain_blocked}",
"status": "ok",
"detail": f"SHA-256 dedup skipped {crawl_res.content_dedup_skipped}, URL dedup={crawl_res.url_dedup_skipped}, HTTP 404={crawl_res.http_errors}, atomic JSONL={atomic_jsonl_bytes} B.",
},
],
"bars": [
{
"id": "bar_vfs_disk_leak_stages",
"title": "VFS 50 GiB Deleted-Log Lifecycle: df Reported vs du Apparent (GiB)",
"metric_label": "GiB",
"items": [
{"label": "df_before_rm", "value": df_before_rm, "display": f"{df_before_rm:.1f} GiB", "css_class": "is-mid"},
{"label": "du_before_rm", "value": du_before_rm, "display": f"{du_before_rm:.1f} GiB", "css_class": "is-mid"},
{"label": "df_after_rm_open_fd", "value": df_after_rm, "display": f"{df_after_rm:.1f} GiB (ghost!)", "css_class": "is-slow"},
{"label": "du_after_rm", "value": du_after_rm, "display": f"{du_after_rm:.1f} GiB", "css_class": "is-fast"},
{"label": "df_after_proc_truncate", "value": df_after_trunc, "display": f"{df_after_trunc:.1f} GiB (freed)", "css_class": "is-fast"},
],
},
{
"id": "bar_makefile_dag_timings",
"title": "Simulated Makefile Work-Span DAG Latency (Serial -j1, Parallel -j2, Incremental)",
"metric_label": "Seconds",
"items": [
{"label": "makefile_full_j1", "value": plan_j1["rebuilt_tp"], "display": f"{plan_j1['rebuilt_tp']:.1f}s (T1)", "css_class": "is-slow"},
{"label": "makefile_full_j2", "value": plan_j2["rebuilt_tp"], "display": f"{plan_j2['rebuilt_tp']:.1f}s ({plan_j2['parallel_speedup']:.2f}x)", "css_class": "is-fast"},
{"label": "makefile_incremental_j2", "value": plan_inc["rebuilt_tp"], "display": f"{plan_inc['rebuilt_tp']:.1f}s (2/4 skipped)", "css_class": "is-fast"},
{"label": "brent_critical_span_t_inf", "value": plan_j2["full_dag_t_inf"], "display": f"{plan_j2['full_dag_t_inf']:.1f}s (T_inf)", "css_class": "is-mid"},
],
},
{
"id": "bar_scheduler_fleet_concurrency",
"title": "100-Node Fleet Peak Concurrent Workers (Unprotected Cron vs systemd Jitter)",
"metric_label": "Concurrent Workers",
"items": [
{"label": "cron_overlap_stampede_peak", "value": float(sched_sim["unjittered_fleet_peak"]), "display": f"{sched_sim['unjittered_fleet_peak']} workers", "css_class": "is-slow"},
{"label": "cron_single_cycle_herd", "value": 100.0, "display": "100 workers", "css_class": "is-mid"},
{"label": "systemd_jitter_45s_peak", "value": float(sched_sim["systemd_jitter_fleet_peak"]), "display": f"{sched_sim['systemd_jitter_fleet_peak']} workers", "css_class": "is-fast"},
{"label": "littles_law_expected_c", "value": sched_sim["littles_law_expected_concurrency"], "display": f"{sched_sim['littles_law_expected_concurrency']:.2f} avg", "css_class": "is-fast"},
],
},
{
"id": "bar_crawler_dedup_and_ssrf",
"title": "Offline CLI Crawler Funnel (URLs, SHA-256 Unique Docs, Blocked SSRF)",
"metric_label": "Count",
"items": [
{"label": "urls_visited", "value": float(crawl_res.urls_visited), "display": f"{crawl_res.urls_visited} fetched", "css_class": "is-mid"},
{"label": "unique_sha256_docs", "value": float(crawl_res.unique_documents), "display": f"{crawl_res.unique_documents} saved", "css_class": "is-fast"},
{"label": "sha256_content_dups_skipped", "value": float(crawl_res.content_dedup_skipped), "display": f"{crawl_res.content_dedup_skipped} dedup", "css_class": "is-fast"},
{"label": "ssrf_offdomain_blocked", "value": float(crawl_res.ssrf_or_domain_blocked), "display": f"{crawl_res.ssrf_or_domain_blocked} blocked", "css_class": "is-slow"},
],
},
],
"tables": [
{
"id": "table_posix_permissions_and_vfs",
"title": "POSIX Bitmask Resolution, Sticky Guard & VFS Open-FD Refcount Audit",
"columns": ["scenario", "mode_or_nlink", "open_fd_or_sticky", "df_vs_du_or_ls", "verdict"],
"rows": [
["file_default_0666_umask_0022", perm_file["octal_str"], perm_file["binary_rwx"], perm_file["ls_string"], "OK"],
["dir_isolated_0777_umask_0027", perm_dir["octal_str"], perm_dir["binary_rwx"], perm_dir["ls_string"], "OK"],
["tmp_sticky_1777_unlink_other", perm_sticky["octal_str"], f"owner_ok={sticky_owner_ok}/other_blk={sticky_other_blocked}", perm_sticky["ls_string"], "PROTECTED"],
["deleted_50g_log_post_rm", f"i_nlink={unlink_info['nlink']}", f"open_fd={unlink_info['open_fd_count']}", f"df={df_after_rm:.1f}G / du={du_after_rm:.1f}G", "GHOST_LEAK"],
["proc_fd_truncate_o_append", f"i_nlink={unlink_info['nlink']}", f"closed_reclaimed={reclaimed_on_close}", f"df={df_after_trunc:.1f}G / hole={trunc_info['sparse_hole_risk']}", "RECLAIMED"],
],
},
{
"id": "table_fd_redirection_and_makefile_dag",
"title": "Bash dup2 FD Routing & Real Makefile Incremental / Crash-Safety Audit",
"columns": ["scenario", "fd1_or_rebuilt", "fd2_or_skipped", "invariant_check", "status"],
"rows": [
["bash_correct_gt_log_2gt_1", fd_correct["fd_1_target"], fd_correct["fd_2_target"], f"shared_desc={fd_correct['shared_open_file_description']}", "SAFE"],
["bash_bug_2gt_1_gt_log", fd_bugged["fd_1_target"], fd_bugged["fd_2_target"], f"stderr_leaked_tty={fd_bugged['stderr_leaked_to_tty']}", "STDERR_LOST"],
["bash_clobber_gt_log_2gt_log", fd_clobber["fd_1_target"], fd_clobber["fd_2_target"], f"clobber_race={fd_clobber['clobber_race']}", "RACE_CORRUPTION"],
["makefile_inc_touch_engine", ",".join(inc_rebuilt_files), ",".join(plan_inc["skipped_targets"]), f"Tp={plan_inc['rebuilt_tp']:.1f}s (-j2)", "MINIMAL_REBUILD"],
["makefile_crash_no_del_vs_del", f"no_del_skip={ 'data/corpus.jsonl' in followup_poisoned['skipped_targets'] }", f"with_del_rebuild={ 'data/corpus.jsonl' in followup_repaired['rebuilt_targets'] }", f"real_mk_has_del={parsed_mk['delete_on_error']}", "GUARD_VERIFIED"],
],
},
{
"id": "table_scheduler_and_psi",
"title": "Cron Overlap Stampede vs systemd Jitter & cgroups v2 PSI Telemetry",
"columns": ["engine_or_metric", "period_or_window", "concurrency_or_some", "peak_or_full", "outcome"],
"rows": [
["cron_vixie_quirk_0_9_13_star_5", "DOM=13 & DOW=Fri", f"quirk_union={cron_quirk['dom_or_dow_quirk']}", "61 runs/yr", "AMBIGUOUS_OR"],
["cron_unprotected_100_nodes", "T_p=60s / T_e=150s", f"single_node={sched_sim['single_node_cron_peak']}x", f"fleet_peak={sched_sim['unjittered_fleet_peak']}", "OOM_STAMPEDE"],
["flock_plus_systemd_jitter_45s", "J=45s, E[C]=11.11", f"single_flock={sched_sim['single_node_flock_peak']} (skip={sched_sim['flock_ticks_skipped']})", f"fleet_peak={sched_sim['systemd_jitter_fleet_peak']}", f"-{sched_sim['fleet_peak_reduction_pct']:.1f}%_PEAK"],
["cgroups_v2_psi_healthy", "10.0s window", f"some={psi_healthy['some_pct']}%", f"full={psi_healthy['full_pct']}%", f"oomd_risk={psi_healthy['oomd_thrashing_risk']}"],
["cgroups_v2_psi_thrashing", "10.0s window", f"some={psi_thrash['some_pct']}%", f"full={psi_thrash['full_pct']}%", f"oomd_risk={psi_thrash['oomd_thrashing_risk']}"],
],
},
{
"id": "table_offline_crawler_docs",
"title": "Offline Ephemeral HTTP CLI Crawler Corpus & Security Boundary Sample",
"columns": ["url_path", "status", "word_count", "sha256_prefix", "title"],
"rows": [
[
urlsplit(doc.url).path or "/",
doc.status_code,
doc.word_count,
doc.sha256[:12],
doc.title,
]
for doc in crawl_res.documents
],
},
],
}
return {
"config": {"quick": bool(quick), "lab_root": str(_LAB_ROOT.name)},
"workbench_panels": workbench_panels,
"posix_and_vfs": {
"perm_file": perm_file,
"perm_dir": perm_dir,
"perm_sticky": perm_sticky,
"sticky_other_blocked": sticky_other_blocked,
"sticky_owner_ok": sticky_owner_ok,
"df_before_rm_gib": df_before_rm,
"du_before_rm_gib": du_before_rm,
"df_after_rm_gib": df_after_rm,
"du_after_rm_gib": du_after_rm,
"df_after_proc_truncate_gib": df_after_trunc,
"lsof_deleted_open": lsof_rows,
"truncate_info": trunc_info,
"reclaimed_on_close": reclaimed_on_close,
},
"makefile_and_scheduler": {
"fd_correct": fd_correct,
"fd_bugged": fd_bugged,
"fd_clobber": fd_clobber,
"parsed_makefile_meta": {
"phony_targets": parsed_mk["phony_targets"],
"delete_on_error": parsed_mk["delete_on_error"],
"oneshell": parsed_mk["oneshell"],
"shell": parsed_mk["shell"],
"rule_count": len(rules),
},
"plan_j1": plan_j1,
"plan_j2": plan_j2,
"plan_incremental": plan_inc,
"followup_poisoned_no_delete_on_error": followup_poisoned,
"followup_repaired_with_delete_on_error": followup_repaired,
"cron_quirk": cron_quirk,
"scheduler_fleet_sim": sched_sim,
"psi_healthy": psi_healthy,
"psi_thrash": psi_thrash,
},
"local_crawl_pipeline": {
"seed_url": crawl_res.seed_url,
"urls_visited": crawl_res.urls_visited,
"unique_documents": crawl_res.unique_documents,
"content_dedup_skipped": crawl_res.content_dedup_skipped,
"url_dedup_skipped": crawl_res.url_dedup_skipped,
"ssrf_or_domain_blocked": crawl_res.ssrf_or_domain_blocked,
"http_errors": crawl_res.http_errors,
"blocked_targets": list(crawl_res.blocked_targets),
"atomic_jsonl_bytes": atomic_jsonl_bytes,
"atomic_jsonl_lines": atomic_jsonl_lines,
},
}
def main() -> int:
parser = argparse.ArgumentParser(description="Run Lab 01 GNU/Linux & CLI Crawler Workbench Demo.")
parser.add_argument("--quick", action="store_true", help="Run fast deterministic demo suite.")
parser.add_argument(
"--output",
type=str,
default="artifacts/t2_ch01_workbench_results.json",
help="Path for JSON results export.",
)
args = parser.parse_args()
payload = run_demo_suite(quick=args.quick)
out_path = Path(args.output)
if not out_path.is_absolute():
out_path = _LAB_ROOT / out_path
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", newline="\n")
pv = payload["posix_and_vfs"]
ms = payload["makefile_and_scheduler"]
cp = payload["local_crawl_pipeline"]
print("[1] POSIX Permissions & VFS 50 GiB Deleted-Log Open-FD Audit")
print(
f" umask 0022 file={pv['perm_file']['octal_str']} ({pv['perm_file']['ls_string']}) | "
f"umask 0027 dir={pv['perm_dir']['octal_str']} ({pv['perm_dir']['ls_string']}) | "
f"sticky 1777 blocks other={pv['sticky_other_blocked']}"
)
print(
f" after rm: df={pv['df_after_rm_gib']:.1f} GiB vs du={pv['du_after_rm_gib']:.1f} GiB "
f"(lsof +L1 rows={len(pv['lsof_deleted_open'])}) -> /proc/fd truncate df={pv['df_after_proc_truncate_gib']:.1f} GiB"
)
print("[2] Bash dup2 Redirection & Real Makefile DAG / .DELETE_ON_ERROR")
print(
f" >out 2>&1 -> fd2={ms['fd_correct']['fd_2_target']} (shared={ms['fd_correct']['shared_open_file_description']}) | "
f"2>&1 >out -> fd2={ms['fd_bugged']['fd_2_target']} (leaked={ms['fd_bugged']['stderr_leaked_to_tty']})"
)
print(
f" Makefile rules={ms['parsed_makefile_meta']['rule_count']} T1={ms['plan_j1']['full_dag_t1']}s "
f"-j2 Tp={ms['plan_j2']['rebuilt_tp']}s ({ms['plan_j2']['parallel_speedup']}x) | "
f"inc rebuilt={ms['plan_incremental']['rebuilt_targets']}"
)
print("[3] Cron Overlap Stampede vs flock + systemd Jitter & cgroups v2 PSI")
sim = ms["scheduler_fleet_sim"]
print(
f" Cron quirk={ms['cron_quirk']['dom_or_dow_quirk']} | single overlap={sim['single_node_cron_peak']} "
f"vs flock={sim['single_node_flock_peak']} | 100-node peak {sim['unjittered_fleet_peak']} -> "
f"{sim['systemd_jitter_fleet_peak']} (-{sim['fleet_peak_reduction_pct']}%)"
)
print(
f" PSI healthy={ms['psi_healthy']['some_pct']}%/{ms['psi_healthy']['full_pct']}% | "
f"thrashing={ms['psi_thrash']['some_pct']}%/{ms['psi_thrash']['full_pct']}% "
f"(oomd_risk={ms['psi_thrash']['oomd_thrashing_risk']})"
)
print("[4] Offline Ephemeral HTTP CLI Crawler & Atomic JSONL Persistence")
print(
f" visited={cp['urls_visited']} unique={cp['unique_documents']} "
f"sha256_dedup={cp['content_dedup_skipped']} url_dedup={cp['url_dedup_skipped']} "
f"blocked={cp['ssrf_or_domain_blocked']} http_404={cp['http_errors']} jsonl={cp['atomic_jsonl_bytes']}B"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""16 deterministic verification contracts for Lab 01 (linux_crawler_lab)."""
from __future__ import annotations
import ast
import json
import socket
import subprocess
import sys
import threading
from pathlib import Path
from typing import Any
from urllib.request import Request, build_opener
import pytest
from pydantic import ValidationError
from linux_crawler_lab import (
CronScheduleSpec,
LocalFixtureServer,
PosixPermissionSpec,
SafeHTTPRedirectHandler,
SSRFBlockedError,
VirtualFileSystem,
atomic_write_json,
atomic_write_jsonl,
canonicalize_url,
check_crawler_health,
check_directory_access,
cli_main,
compute_psi_pressure,
crawl_site,
install_signal_handlers,
is_url_allowed,
parse_cron_expression,
parse_makefile,
plan_makefile_rebuild,
resolve_posix_permissions,
restore_signal_handlers,
simulate_cron_vs_systemd_fleet,
simulate_fd_redirection,
validate_target_url,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
GIB = 1024**3
def test_01_posix_umask_resolution_and_special_bits_ls_string() -> None:
f_res = resolve_posix_permissions(0o666, 0o022, is_dir=False)
assert f_res["octal_str"] == "0644"
assert f_res["ls_string"] == "-rw-r--r--"
d_res = resolve_posix_permissions(0o777, 0o027, is_dir=True)
assert d_res["octal_str"] == "0750"
assert d_res["ls_string"] == "drwxr-x---"
suid_exec = resolve_posix_permissions(0o755, 0o000, is_dir=False, special_bits=0o4000)
assert suid_exec["ls_string"] == "-rwsr-xr-x"
# Uppercase S when underlying owner execute bit is cleared
suid_no_x = resolve_posix_permissions(0o644, 0o000, is_dir=False, special_bits=0o4000)
assert suid_no_x["ls_string"] == "-rwSr--r--"
def test_02_sticky_bit_and_directory_rwx_semantics() -> None:
sticky_dir = resolve_posix_permissions(0o777, 0o000, is_dir=True, special_bits=0o1000)
assert sticky_dir["octal_str"] == "1777"
assert sticky_dir["ls_string"] == "drwxrwxrwt"
# Mode 0111 (--x--x--x): traverse allowed, listing denied
assert check_directory_access(0o111, "traverse", 0, 1001, 1002, "other") is True
assert check_directory_access(0o111, "list", 0, 1001, 1002, "other") is False
# Sticky 1777: non-owner cannot unlink another user's file; owner and dir owner can
assert check_directory_access(0o1777, "unlink", dir_uid=0, file_uid=1001, caller_uid=1002, caller_class="other") is False
assert check_directory_access(0o1777, "unlink", dir_uid=0, file_uid=1001, caller_uid=1001, caller_class="other") is True
assert check_directory_access(0o1777, "unlink", dir_uid=1000, file_uid=1001, caller_uid=1000, caller_class="owner") is True
def test_03_vfs_deleted_50gb_log_inode_refcount_and_o_append_truncate() -> None:
vfs = VirtualFileSystem()
path = "/var/log/crawler/payloads.log"
vfs.create_file(path, size_bytes=0)
fd = vfs.open_fd(pid=18422, path=path, o_append=True)
vfs.write_fd(pid=18422, fd=fd, num_bytes=50 * GIB)
assert vfs.df_used_bytes() == 50 * GIB
assert vfs.du_apparent_bytes() == 50 * GIB
res_unlink = vfs.unlink(path)
assert res_unlink["nlink"] == 0
assert res_unlink["open_fd_count"] == 1
assert res_unlink["reclaimed"] is False
# Classic paradox: df stays 50 GiB while du drops to 0 GiB
assert vfs.df_used_bytes() == 50 * GIB
assert vfs.du_apparent_bytes() == 0
assert len(vfs.lsof_deleted_open()) == 1
# Hard-linked file survives unlink while second path exists
vfs.create_file("/var/log/hard_a", size_bytes=1024)
vfs.hard_link("/var/log/hard_a", "/var/log/hard_b")
assert vfs.unlink("/var/log/hard_a")["reclaimed"] is False
assert vfs.du_apparent_bytes() == 1024
assert vfs.unlink("/var/log/hard_b")["reclaimed"] is True
# Safe /proc/<pid>/fd truncate with O_APPEND=True frees physical blocks without sparse hole
trunc = vfs.truncate_proc_fd(pid=18422, fd=fd)
assert trunc["freed_bytes"] == 50 * GIB
assert trunc["sparse_hole_risk"] is False
assert vfs.df_used_bytes() == 0
assert vfs.close_fd(pid=18422, fd=fd) is True
def test_04_fd_dup2_redirection_left_to_right_order_and_stderr_leak() -> None:
correct = simulate_fd_redirection([">out.log", "2>&1"])
assert correct["fd_1_target"] == "out.log"
assert correct["fd_2_target"] == "out.log"
assert correct["shared_open_file_description"] is True
assert correct["stderr_leaked_to_tty"] is False
bugged = simulate_fd_redirection(["2>&1", ">out.log"])
assert bugged["fd_1_target"] == "out.log"
assert bugged["fd_2_target"] == "tty"
assert bugged["shared_open_file_description"] is False
assert bugged["stderr_leaked_to_tty"] is True
clobber = simulate_fd_redirection([">out.log", "2>out.log"])
assert clobber["clobber_race"] is True
stderr_pipe = simulate_fd_redirection(["|pipe", "2>&1", ">/dev/null"])
assert stderr_pipe["fd_1_target"] == "/dev/null"
assert stderr_pipe["fd_2_target"] == "pipe_write"
def test_05_real_makefile_dag_parse_incremental_rebuild_and_parallel_work_span() -> None:
mk_text = (LAB_ROOT / "Makefile").read_text(encoding="utf-8")
parsed = parse_makefile(mk_text)
assert parsed["delete_on_error"] is True
assert parsed["oneshell"] is True
for phony in ("all", "crawl", "extract", "report", "test", "clean"):
assert phony in parsed["phony_targets"]
rules = parsed["rules"]
weights = {
"data/raw_pages.json": 4.0,
"data/corpus.jsonl": 2.0,
"artifacts/posix_audit.json": 5.0,
"artifacts/crawl_report.json": 1.0,
}
base_mtimes: dict[str, float | None] = {
"src/linux_crawler_lab/cli_crawler.py": 100.0,
"src/linux_crawler_lab/posix_and_make_engine.py": 100.0,
}
j1 = plan_makefile_rebuild(rules, base_mtimes, goal="all", jobs=1, work_estimates=weights)
j2 = plan_makefile_rebuild(rules, base_mtimes, goal="all", jobs=2, work_estimates=weights)
assert j1["full_dag_t1"] == pytest.approx(12.0)
assert j1["full_dag_t_inf"] == pytest.approx(7.0)
assert j2["rebuilt_tp"] == pytest.approx(7.0)
assert j2["parallel_speedup"] > 1.5
# Touching only posix_and_make_engine.py skips raw_pages.json and corpus.jsonl
inc_mtimes = dict(j2["updated_mtimes"])
inc_mtimes["src/linux_crawler_lab/posix_and_make_engine.py"] = 5000.0
inc = plan_makefile_rebuild(rules, inc_mtimes, goal="all", jobs=2, work_estimates=weights)
assert "data/raw_pages.json" in inc["skipped_targets"]
assert "data/corpus.jsonl" in inc["skipped_targets"]
assert "artifacts/posix_audit.json" in inc["rebuilt_targets"]
assert "artifacts/crawl_report.json" in inc["rebuilt_targets"]
def test_06_makefile_delete_on_error_prevents_stale_corrupted_artifact() -> None:
rules = parse_makefile((LAB_ROOT / "Makefile").read_text(encoding="utf-8"))["rules"]
base_mtimes: dict[str, float | None] = {
"src/linux_crawler_lab/cli_crawler.py": 100.0,
"src/linux_crawler_lab/posix_and_make_engine.py": 100.0,
}
# Without .DELETE_ON_ERROR, crashed target keeps new mtime and poisons next build
crash_unsafe = plan_makefile_rebuild(
rules, base_mtimes, goal="all", failed_target="data/corpus.jsonl", delete_on_error=False, failure_timestamp=8000.0
)
next_unsafe = plan_makefile_rebuild(rules, crash_unsafe["updated_mtimes"], goal="all")
assert "data/corpus.jsonl" in next_unsafe["skipped_targets"]
# With .DELETE_ON_ERROR, crashed target is removed so next build repairs it
crash_safe = plan_makefile_rebuild(
rules, base_mtimes, goal="all", failed_target="data/corpus.jsonl", delete_on_error=True, failure_timestamp=8000.0
)
next_safe = plan_makefile_rebuild(rules, crash_safe["updated_mtimes"], goal="all")
assert "data/corpus.jsonl" in next_safe["rebuilt_targets"]
def test_07_cron_parser_vixie_dom_or_dow_quirk_and_overlap_stampede() -> None:
quirk = parse_cron_expression("0 9 13 * 5")
assert quirk["dom_or_dow_quirk"] is True
assert quirk["minutes"] == [0]
assert quirk["hours"] == [9]
assert quirk["dows"] == [5]
normal = parse_cron_expression("*/15 0-6 * * 1-5")
assert normal["dom_or_dow_quirk"] is False
assert normal["minutes"] == [0, 15, 30, 45]
sim = simulate_cron_vs_systemd_fleet(
period_sec=60.0, exec_sec=150.0, fleet_nodes=100, jitter_sec=45.0, horizon_sec=300.0
)
assert sim["utilization_rho"] == pytest.approx(2.5)
assert sim["single_node_cron_peak"] == 3
assert sim["single_node_flock_peak"] == 1
assert sim["flock_ticks_skipped"] >= 3
def test_08_systemd_timer_jitter_concurrency_collapse_and_psi_calculation() -> None:
sim = simulate_cron_vs_systemd_fleet(
period_sec=60.0, exec_sec=150.0, fleet_nodes=100, jitter_sec=45.0, horizon_sec=300.0
)
assert sim["unjittered_fleet_peak"] == 300
assert sim["systemd_jitter_fleet_peak"] <= 15
assert sim["fleet_peak_reduction_pct"] >= 90.0
assert sim["littles_law_expected_concurrency"] == pytest.approx(100.0 * 5.0 / 45.0, abs=0.05)
psi = compute_psi_pressure(
some_intervals=[(0.5, 2.34)],
full_intervals=[(0.8, 1.45), (1.0, 1.80)], # Overlapping intervals merged accurately
window_sec=10.0,
)
assert psi["some_pct"] == pytest.approx(18.4, abs=0.05)
assert psi["full_pct"] == pytest.approx(10.0, abs=0.05)
assert psi["oomd_thrashing_risk"] is True
def test_09_url_canonicalization_allowlist_and_ssrf_bypass_rejection() -> None:
canon_slash = canonicalize_url("HTTPS://Example.COM.:443/docs/../docs/linux/?b=2&utm_source=cron&a=1#inode")
assert canon_slash == "https://example.com/docs/linux/?a=1&b=2"
canon_noslash = canonicalize_url("HTTPS://Example.COM.:443/docs/../docs/linux?b=2&utm_source=cron&a=1#inode")
assert canon_noslash == "https://example.com/docs/linux?a=1&b=2"
# Disallowed schemes & userinfo rejected
with pytest.raises(ValueError):
canonicalize_url("file:///etc/passwd")
with pytest.raises(ValueError):
canonicalize_url("http://trusted.com@evil.com/path")
# Strict allowlist blocks substring bypass & metadata SSRF
assert is_url_allowed("https://docs.example.com/page", ("example.com",))[0] is True
assert is_url_allowed("https://evil-example.com/page", ("example.com",))[0] is False
assert is_url_allowed("https://example.com.attacker.io/", ("example.com",))[0] is False
assert is_url_allowed("http://169.254.169.254/latest/meta-data", ("127.0.0.1", "example.com"))[0] is False
assert is_url_allowed("http://127.0.0.1:8080/", ("example.com",))[0] is False
def test_10_authentic_bash_systemd_and_crontab_artifacts_hardening_guards() -> None:
sh_txt = (LAB_ROOT / "scripts" / "crawl_pipeline.sh").read_text(encoding="utf-8")
assert "set -Eeuo pipefail" in sh_txt
assert "trap cleanup EXIT INT TERM" in sh_txt
assert "mktemp -d" in sh_txt
assert "flock -n 9" in sh_txt
assert '> "$LOG_FILE" 2>&1' in sh_txt
assert 'readonly SCRIPT_DIR="$(' not in sh_txt
assert 'readonly LAB_ROOT="$(' not in sh_txt
assert 'mktemp -p "$out_dir"' in sh_txt
svc_txt = (LAB_ROOT / "deploy" / "fsds-crawler.service").read_text(encoding="utf-8")
for key in (
"MemoryHigh=",
"MemoryMax=",
"CPUQuota=",
"KillMode=mixed",
"ProtectSystem=strict",
"PrivateTmp=yes",
"StateDirectory=fsds-crawler",
"LogsDirectory=fsds-crawler",
"RuntimeDirectory=fsds-crawler",
"Environment=OUTPUT_JSONL=/var/lib/fsds-crawler/corpus.jsonl",
"Environment=REPORT_JSON=/var/lib/fsds-crawler/report.json",
"Environment=LOG_FILE=/var/log/fsds-crawler/crawl.log",
"Environment=LOCK_FILE=/run/fsds-crawler/crawl.lock",
):
assert key in svc_txt
assert "/run/lock/fsds-crawler.lock" not in svc_txt
tmr_txt = (LAB_ROOT / "deploy" / "fsds-crawler.timer").read_text(encoding="utf-8")
for key in ("OnCalendar=", "RandomizedDelaySec=", "AccuracySec=1s", "Persistent=true"):
assert key in tmr_txt
cron_txt = (LAB_ROOT / "deploy" / "crontab.example").read_text(encoding="utf-8")
assert "PATH=" in cron_txt
assert "flock -n" in cron_txt
assert "> /var/log/fsds-crawler.log 2>&1" in cron_txt
assert "*/30 * * * * /usr/bin/flock" in cron_txt
assert "*/5 * * * * fsds" not in cron_txt
def test_11_local_http_crawler_sha256_dedup_and_atomic_jsonl_replace(tmp_path: Path) -> None:
with LocalFixtureServer() as base_url:
report = crawl_site(seed_url=base_url, allowed_hosts=("127.0.0.1",), max_pages=15, max_depth=3)
assert report.urls_visited == 9
assert report.unique_documents == 7
assert report.content_dedup_skipped == 1 # /docs/mirror shares body with /docs/inode-leak
assert report.url_dedup_skipped >= 1 # /docs/linux?utm_source=cron#inode collapsed
assert report.ssrf_or_domain_blocked == 2 # evil-example.com + 169.254.169.254
assert report.http_errors == 1 # /missing-404
out_jsonl = tmp_path / "corpus.jsonl"
atomic_write_jsonl(out_jsonl, [{"url": d.url, "sha256": d.sha256} for d in report.documents])
lines = out_jsonl.read_text(encoding="utf-8").splitlines()
assert len(lines) == 7
assert not any(p.name.endswith(".tmp") for p in tmp_path.iterdir())
def test_12_cli_crawler_deterministic_exit_codes_0_2_3(tmp_path: Path) -> None:
out_json = tmp_path / "report.json"
# Exit 0: valid local fixture crawl
rc0 = cli_main(["--serve-fixtures", "--max-pages", "8", "--report-json", str(out_json)])
assert rc0 == 0
assert json.loads(out_json.read_text(encoding="utf-8"))["unique_documents"] >= 5
# Exit 2: invalid CLI usage / disallowed scheme / seed outside allowlist
assert cli_main(["--max-pages", "0"]) == 2
assert cli_main(["--seed-url", "file:///etc/passwd"]) == 2
assert cli_main(["--seed-url", "http://127.0.0.1:9999/", "--allow-host", "example.com"]) == 2
# Exit 3: strict --fail-on-http-error when fixture includes /missing-404
rc3 = cli_main(["--serve-fixtures", "--max-pages", "12", "--fail-on-http-error"])
assert rc3 == 3
def test_13_pydantic_contracts_reject_invalid_modes_and_extra_fields(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
with pytest.raises(ValidationError):
PosixPermissionSpec(base_mode=0o777, umask=0o022, extra_key=123) # type: ignore[call-arg]
with pytest.raises(ValidationError):
PosixPermissionSpec(base_mode=0o1000, umask=0o022)
with pytest.raises(ValidationError):
PosixPermissionSpec(special_bits=0o0777)
with pytest.raises(ValidationError):
CronScheduleSpec(expression="* * * * *", period_sec=0.0, exec_sec=10.0, fleet_nodes=10, jitter_sec=5.0)
with pytest.raises(ValueError):
parse_cron_expression("* * * *") # only 4 fields
# Atomic JSON write leaves pre-existing target intact & cleans up .tmp if os.replace fails
target = tmp_path / "state.json"
atomic_write_json(target, {"version": 1})
def _boom(*_args: object, **_kwargs: object) -> None:
raise OSError("Simulated power loss during rename")
monkeypatch.setattr("linux_crawler_lab.cli_crawler.os.replace", _boom)
with pytest.raises(OSError):
atomic_write_json(target, {"version": 2})
assert json.loads(target.read_text(encoding="utf-8")) == {"version": 1}
assert [p.name for p in tmp_path.iterdir()] == ["state.json"]
def test_14_cli_demo_workbench_json_and_zero_forbidden_imports(tmp_path: Path) -> None:
out_json = tmp_path / "t2_ch01_workbench_results.json"
proc = subprocess.run(
[sys.executable, str(LAB_ROOT / "scripts" / "run_lab_demo.py"), "--quick", "--output", str(out_json)],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=False,
)
assert proc.returncode == 0, f"Demo CLI failed:\n{proc.stderr}"
for marker in ("[1]", "[2]", "[3]", "[4]"):
assert marker in proc.stdout
data = json.loads(out_json.read_text(encoding="utf-8"))
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
forbidden = {"pickle", "_pickle", "cPickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
py_files = sorted(
list((LAB_ROOT / "src").rglob("*.py"))
+ list((LAB_ROOT / "scripts").rglob("*.py"))
+ list((LAB_ROOT / "tests").rglob("*.py"))
)
assert len(py_files) >= 5
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:
root = alias.name.split(".")[0]
assert root not in forbidden, f"Forbidden import {root} in {py_file}"
elif isinstance(node, ast.ImportFrom) and node.module:
root = node.module.split(".")[0]
assert root not in forbidden, f"Forbidden import {root} in {py_file}"
def test_15_ssrf_redirect_301_302_307_308_and_post_dns_blocked(
monkeypatch: pytest.MonkeyPatch,
) -> None:
# 1. Loopback blocked unless allow_loopback_test=True explicitly enabled
assert validate_target_url("http://127.0.0.1:8080/health", allow_loopback_test=False)[0] is False
assert validate_target_url("http://127.0.0.1:8080/health", allow_loopback_test=True)[0] is True
assert validate_target_url(
"http://169.254.169.254/latest/meta-data/", allow_loopback_test=True
)[0] is False
assert validate_target_url(
"http://[::ffff:169.254.169.254]/", allow_loopback_test=True
)[0] is False
assert validate_target_url("http://10.0.0.1/internal", allow_loopback_test=True)[0] is False
assert validate_target_url("http://224.0.0.1/", allow_loopback_test=True)[0] is False
# 2. Post-DNS rebinding to link-local / private / loopback IPs blocked
orig_getaddrinfo = socket.getaddrinfo
def _fake_getaddrinfo(
host: str, port: Any, *args: Any, **kwargs: Any
) -> list[tuple[Any, ...]]:
if host == "rebind-meta.example.com":
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("169.254.169.254", int(port or 80)))]
if host == "rebind-loopback.example.com":
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", int(port or 80)))]
if host == "docs.example.com":
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", int(port or 80)))]
return orig_getaddrinfo(host, port, *args, **kwargs)
monkeypatch.setattr(socket, "getaddrinfo", _fake_getaddrinfo)
assert validate_target_url("https://rebind-meta.example.com/secret", ("example.com",))[0] is False
assert (
validate_target_url("https://rebind-loopback.example.com/secret", ("example.com",))[0]
is False
)
assert validate_target_url("https://docs.example.com/ok", ("example.com",))[0] is True
# 3. Live local redirect server proving 301/302/307/308 SSRF hops are blocked BEFORE connecting
redirect_pages = {
"/": (
200,
"<html><title>Redirect Hub</title><body>"
'<a href="/hop-302-meta">Meta 302</a>'
'<a href="/hop-301-priv">Priv 301</a>'
'<a href="/hop-307-rebind">Rebind 307</a>'
'<a href="/hop-308-file">File 308</a>'
'<a href="/hop-safe">Safe 302</a>'
"</body></html>",
),
"/hop-302-meta": (302, "", {"Location": "http://169.254.169.254/latest/meta-data/"}),
"/hop-301-priv": (301, "", {"Location": "http://10.0.0.5/admin"}),
"/hop-307-rebind": (307, "", {"Location": "http://rebind-meta.example.com/token"}),
"/hop-308-file": (308, "", {"Location": "file:///etc/passwd"}),
"/hop-safe": (302, "", {"Location": "/safe-landing"}),
"/safe-landing": (
200,
"<html><title>Safe Landing</title><body>Safe redirect on 127.0.0.1</body></html>",
),
}
with LocalFixtureServer(redirect_pages) as base_url:
# Direct SafeHTTPRedirectHandler check on 302 -> 169.254.169.254
opener = build_opener(SafeHTTPRedirectHandler(("127.0.0.1",), allow_loopback_test=True))
with pytest.raises(SSRFBlockedError):
opener.open(Request(f"{base_url}hop-302-meta"), timeout=2.0)
# Crawler follows /hop-safe -> /safe-landing while blocking all 4 SSRF redirects
report = crawl_site(
seed_url=base_url, allowed_hosts=("127.0.0.1",), max_pages=10, max_depth=2
)
assert report.ssrf_or_domain_blocked == 4
assert report.unique_documents == 2
assert any(d.url.endswith("/safe-landing") for d in report.documents)
def test_16_graceful_shutdown_sigterm_and_healthcheck(tmp_path: Path) -> None:
stop_event = threading.Event()
healthy = check_crawler_health(output_dir=tmp_path, stop_event=stop_event, probe_fixture=True)
assert healthy["ready"] is True
assert healthy["status"] == "ready"
assert healthy["output_dir_writable"] is True
assert healthy["fixture_probe_ok"] is True
prev, sig_state = install_signal_handlers(stop_event)
try:
stop_event.set()
draining = check_crawler_health(
output_dir=tmp_path, stop_event=stop_event, probe_fixture=False
)
assert draining["ready"] is False
assert draining["status"] == "draining"
assert draining["shutting_down"] is True
with LocalFixtureServer() as base_url:
report = crawl_site(
seed_url=base_url, allowed_hosts=("127.0.0.1",), stop_event=stop_event
)
assert report.interrupted is True
assert report.urls_visited == 0
assert sig_state["signum"] is None
finally:
restore_signal_handlers(prev)
fd=3 ghi tệp /var/log/crawler/payloads.log (50.0 GiB). Kỹ sư trực chạy rm /var/log/crawler/payloads.log nhưng df -h vẫn báo 50.0 GiB chiếm dụng trong khi du -sh chỉ báo 0.0 GiB. Vì sao và xử lý không gián đoạn dịch vụ thế nào?/proc/<pid>/fd/3 (khi có cờ O_APPEND) hoặc gửi SIGUSR1 giải phóng 50.0 GiB ngay lập tức với 0 giây downtime.
/tmp có chế độ 0o1777. Giá trị bát phân hiệu lực của thư mục mới và vai trò của bit 0o1000 là gì?0777 & (~0027 & 0777) = 0750 (drwxr-x---). Với /tmp (1777, drwxrwxrwt), dù other có w+x trên thư mục, nhân Linux chỉ cho phép unlink nếu người gọi là chủ tệp, chủ thư mục hoặc root.
CMD python worker.py (/bin/sh -c) hoặc dạng exec CMD ["python", "worker.py"] (không dùng tini hay đăng ký handler SIGTERM), vì sao kubectl rollout restart bị treo đúng 30s rồi chết với mã thoát 137, và vì sao kill -9 bất lực trước các tiến trình trạng thái Z (Zombie) hoặc D?ENTRYPOINT ["/usr/bin/tini", "--"] (hoặc docker run --init) cộng với handler SIGTERM + ghi nguyên tử os.replace() để chuyển tiếp tín hiệu, thu gom zombie Z bằng waitpid, và tránh cắt cụt JSONL khi SIGKILL xảy ra.
cmd > out.log 2>&1 và cmd 2>&1 > out.log trong POSIX shell, kết quả fd[1] (stdout), fd[2] (stderr) và rủi ro nếu thay bằng cmd > out.log 2> out.log là gì?simulate_fd_redirection: 2>&1 > out.log làm fd[2] kẹt ở tty (stderr_leaked_to_tty=True), còn > out.log 2> out.log mở 2 Open File Descriptions tách biệt (clobber_race=True). Chỉ > out.log 2>&1 chia sẻ chung một struct file.
set -Eeuo pipefail, vì sao dòng local res=$(curl -fsSL https://bad.local) hoặc việc xóa tệp khóa rm -f "$LOCK_FILE" trong trap cleanup EXIT lại gây lỗi âm thầm nguy hiểm trong sản xuất?local res; res="$(curl ...)" để set -e bắt đúng lỗi mạng, dùng < <(cmd) thay vì pipe để giữ phạm vi biến, và TUYỆT ĐỐI không unlink tệp flock(2) vì flock gắn vào inode/open-file-description (tự nhả bởi kernel ngay cả khi chết vì SIGKILL).
Makefile có \(T_1 = 12.0\text{ s}\), critical path \(T_\infty = 7.0\text{ s}\)), điều gì xảy ra nếu target data/corpus.jsonl bị sập giữa chừng khi thiếu .DELETE_ON_ERROR:, và vì sao container Alpine musl hay gây sập/chậm cho hệ sinh thái Python AI?-j2 đạt tối đa 7.0s (1.71x). Kiểm thử Lab 01 khẳng định thiếu .DELETE_ON_ERROR khiến data/corpus.jsonl lỗi bị bỏ qua ở lần chạy kế tiếp; ngoài ra luôn dùng readelf -d thay ldd cho tệp lạ.
0 9 13 * 5 và một cụm \(N=100\) máy thu thập dữ liệu chạy định kỳ \(T_{\text{period}} = 60\text{ s}\) gặp đột biến độ trễ \(T_{\text{exec}} = 150\text{ s}\) (bình thường \(\bar{t} = 5\text{ s}\)). Kết quả mô phỏng đúng khi chuyển sang flock -n + systemd (RandomizedDelaySec=45s, AccuracySec=1s) là gì?linux_crawler_lab chứng minh đỉnh 100 nút sập từ 300 xuống 12 (-96.0%), flock -n chặn tích tụ 3x (4 tick bị bỏ qua sạch sẽ), và PSI phân biệt some (>=1 tác vụ nghẽn) với full (MỌI tác vụ không rỗi đều nghẽn — dấu hiệu thrashing tiền-OOM).
2,000 RPS)?is_url_allowed chặn đứng evil-example.com & 169.254.169.254, SHA-256 loại trùng /docs/mirror, os.replace() bảo toàn tệp cũ khi lỗi xảy ra (Test 13), và mã 2 ngăn scheduler lặp vô nghĩa lỗi cấu hình.
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 — Đại số Quyền POSIX, umask & VFS Refcount 50 GiB Open-FD 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết phép toán nhị phân từng bit cho \(m_{\text{eff}} = m_{\text{base}} \land (\neg u_{\text{mask}} \land \text{0o777})\) trên (0o666, 0o022) và (0o777, 0o027), đồng thời đối chiếu định nghĩa hai biến đếm i_nlink và open_fd_refs trên struct inode.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Dùng VirtualFileSystem trong posix_and_make_engine.py để tạo tệp 50 * 1024**3 byte mở qua open_fd(..., o_append=True) và o_append=False, chạy unlink(), đối chiếu df_used_bytes() vs. du_apparent_bytes(), rồi chạy truncate_proc_fd().
Tiêu chí Đáp án & Số đối chứng
Kết quả chuẩn: 0o666 & ~0o022 = 0644 (-rw-r--r--), 0o777 & ~0o027 = 0750 (drwxr-x---), /tmp 1777 (drwxrwxrwt) chặn non-owner unlink. Sau rm, df = 50.0 GiB vs. du = 0.0 GiB (lsof +L1 báo 1 FD); truncate_proc_fd với O_APPEND=True đưa df về 0.0 GiB với sparse_hole_risk=False.
Bài tập 2 — Chuỗi Gọi hệ thống dup2(2), Bẫy PID 1 & Khắc phục Exit 137
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Mô phỏng từng bước bảng fdtable cho hai lệnh cmd > out.log 2>&1 và cmd 2>&1 > out.log bằng cách theo dõi con trỏ tới struct file qua mỗi phép dup2(oldfd, newfd).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy simulate_fd_redirection với cả 4 chuỗi (>out.log 2>&1, 2>&1 >out.log, >out.log 2>out.log, |pipe 2>&1 >/dev/null); sau đó viết Dockerfile chuẩn dùng tini exec-form + trình xử lý SIGTERM và ghi os.replace().
Tiêu chí Đáp án & Số đối chứng
2>&1 > out.log khiến stderr_leaked_to_tty=True (fd[2]=tty); > out.log 2> out.log tạo clobber_race=True; chỉ > out.log 2>&1 đạt shared_open_file_description=True. Với Container PID 1, ENTRYPOINT ["/usr/bin/tini", "--"] + handler SIGTERM loại bỏ treo 30s / mã 137.
Bài tập 3 — Bash Strict Mode (ShellCheck Clean), flock(2) & Quy tắc pipefail
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Rà soát script scripts/crawl_pipeline.sh theo 4 lỗi ShellCheck hay gặp nhất: SC2086 (thiếu ngoặc kép), SC2046 (tách từ $(...)), SC2155 (local x=$(cmd) nuốt mã lỗi), và SC2064 (trap "... $var" giãn sớm).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Giải thích vì sao không bao giờ được xóa tệp LOCK_FILE trong hàm cleanup() và chứng minh bằng sơ đồ inode với 2 tiến trình cạnh tranh flock -n 9.
Tiêu chí Đáp án & Số đối chứng
scripts/crawl_pipeline.sh tách biến trước readonly (khắc phục SC2155), tôn trọng biến môi trường LOCK_FILE/OUTPUT_JSONL/REPORT_JSON/LOG_FILE khớp StateDirectory/LogsDirectory/RuntimeDirectory của fsds-crawler.service, giữ nguyên inode tệp lock dưới flock -n 9, staging cùng filesystem qua mktemp -p chống EXDEV, và deploy/crontab.example dùng đúng chuẩn 5 cột người dùng.
Bài tập 4 — Phân tích Đồ thị Makefile Thực, Work–Span -j(nproc) & .DELETE_ON_ERROR
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dùng parse_makefile nạp tệp Makefile thật của Lab 01, lập ma trận trọng số raw_pages=4s, corpus=2s, posix_audit=5s, report=1s, và tính đường găng \(T_\infty\) cùng cận dưới Brent \(T_p \ge \max(T_1/p, T_\infty)\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi plan_makefile_rebuild với failed_target='data/corpus.jsonl' cho hai trường hợp delete_on_error=False vs. True, rồi thực thi lần make thứ hai để kiểm tra xem target hỏng có bị bỏ qua hay không.
Tiêu chí Đáp án & Số đối chứng
Toàn đồ thị đạt \(T_1 = 12.0\text{ s}\), \(T_\infty = 7.0\text{ s}\), và -j2 đạt \(T_2 = 7.0\text{ s}\) (1.71x). Chạm posix_and_make_engine.py chỉ chạy lại 2/4 tệp (posix_audit.json, crawl_report.json) trong 6.0s. Thiếu .DELETE_ON_ERROR làm data/corpus.jsonl lọt vào skipped_targets dù đã hỏng.
Bài tập 5 — Toán học Chồng lấn Cron, Định luật Little cho systemd Jitter & PSI
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Giải thích bẫy hợp logic DOM OR DOW của 0 9 13 * 5 (~61 lần/năm), và tính số tiến trình chồng lấn \(\lceil T_{\text{exec}} / T_{\text{period}} \rceil\) khi T_exec = 150s, T_period = 60s.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi simulate_cron_vs_systemd_fleet (fleet_nodes=100, jitter_sec=45.0) đối chiếu với công thức Little \(\mathbb{E}[C] = N_{\text{nodes}} \cdot \bar{t} / J\), đồng thời kiểm định compute_psi_pressure với các khoảng giao nhau.
Tiêu chí Đáp án & Số đối chứng
Cron không khóa đạt đỉnh 3x trên 1 nút và 300 toàn cụm 100 nút; flock -n + systemd (RandomizedDelaySec=45s, AccuracySec=1s) giảm đỉnh xuống 12 workers (-96.0%, khớp \(\mathbb{E}[C]=11.11\)). PSI full = 12.5% bật cờ oomd_thrashing_risk=True.
Bài tập 6 — Xây dựng & Kiểm định CLI Crawler Bất khả tri Mạng Ngoài (linux_crawler_lab)
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Đọc cli_crawler.py để nắm quy trình: canonicalize_url (RFC 3986 + lọc utm_*) -> validate_target_url + SafeHTTPRedirectHandler (chặn IP private/link-local hậu DNS & mọi hop chuyển hướng 301/302/307/308) -> HTMLParser -> SHA-256 -> atomic_write_jsonl (mkstemp + fsync + os.replace) -> install_signal_handlers (SIGTERM/SIGINT) & check_crawler_health.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy python scripts/run_lab_demo.py --quick --output artifacts/t2_ch01_workbench_results.json và pytest -p no:cacheprovider -v, kiểm tra cả mã thoát 0, 2, 3, cờ --healthcheck, và AST không import thư viện giải tuần tự không an toàn (pickle, joblib, cloudpickle, dill, shelve, marshal).
Tiêu chí Đáp án & Số đối chứng
Crawler ghé 9 URL trên máy chủ 127.0.0.1 nội bộ, lưu 7 tài liệu duy nhất (2,897 B JSONL), loại 1 bản trùng nội dung SHA-256 (/docs/mirror), gộp 1 URL trùng tracking, chặn 2 liên kết SSRF/ngoài miền (cộng 4 hop redirect SSRF ở Test 15), ghi nhận 1 mã 404, vượt Test 16 (SIGTERM & --healthcheck), và đạt 16/16 pytest.