test_raid_lesson.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The RAID lesson: it leads with continuity and not backup, its drill runs, its figures are computed, it is registered.
  3. docs/wiki/RAID-Levels-Parity-Rebuilds-and-Why-RAID-Is-Continuity-Not-a-Backup.md teaches RAID as a business continuity
  4. control (issue 421). A page that lets RAID pass for a backup, an exercise answer typed by hand and wrong, a drill whose output
  5. differs from the page, a command that could reach a real disk, a vendor ranking, a dead link, a missing registration, a
  6. diagram with no picture or the wrong shape, or a register row with no URL and no date would each teach the wrong thing.
  7. """
  8. import json
  9. import math
  10. import re
  11. import struct
  12. import subprocess
  13. import sys
  14. import textwrap
  15. from pathlib import Path
  16. from wikitext import glossary_text, nav_text
  17. ROOT = Path(__file__).resolve().parent.parent
  18. WIKI = ROOT / "docs" / "wiki"
  19. NAME = "RAID-Levels-Parity-Rebuilds-and-Why-RAID-Is-Continuity-Not-a-Backup"
  20. PAGE = WIKI / f"{NAME}.md"
  21. BCP = "Business-Continuity-and-Disaster-Recovery-BCP-and-DR"
  22. CIA = "The-CIA-Triad-Confidentiality-Integrity-Availability"
  23. BACKUPS = "Backups-Recovery-and-Patching"
  24. DEEP = "Backups-Deep-Dive-3-2-1-1-0-Immutability-and-Restore-Testing"
  25. DATE = "2026-11-01"
  26. EXERCISE = "## Exercise: size a six-drive shelf on paper"
  27. FRAMING = "## RAID keeps the system running; a backup keeps the data recoverable"
  28. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
  29. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  30. WRAPPED = re.compile(
  31. r"!\[(?P<alt>[^\]\n]*)\]\((?P<path>[^)\n]+)\)\n\n<details>\n<summary>Diagram source \(Mermaid\)</summary>\n\n```mermaid\n(?P<src>.*?)\n```\n\n</details>",
  32. re.DOTALL,
  33. )
  34. URL = re.compile(r"\]\(https?://[^)\s]+\)")
  35. STATUS_WORDS = ("Read", "Observed", "Not run", "**est.**", "General knowledge", "Derived")
  36. IPV4 = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  37. BRITISH = ("defence", "behaviour", "colour", "organisation", "centre", "licence", "programme", "analyse", "favour", "realise", "offence", "grey")
  38. VENDORS = (
  39. "seagate",
  40. "western digital",
  41. "toshiba",
  42. "hgst",
  43. "hitachi",
  44. "samsung",
  45. "synology",
  46. "qnap",
  47. "broadcom",
  48. "adaptec",
  49. "dell",
  50. "netapp",
  51. "wd red",
  52. "ironwolf",
  53. "barracuda",
  54. )
  55. TOPICS = (
  56. "## What you will be able to do",
  57. "## What the wiki already says (and the gap)",
  58. FRAMING,
  59. "## The words: striping, mirroring, parity, spares",
  60. "## The levels, side by side",
  61. "## Parity in one XOR, and the price of a small write",
  62. "## When a drive fails: degraded, rebuild and the risk window",
  63. "## The write hole and power loss",
  64. "## Hardware, firmware, software and filesystem RAID",
  65. "## What RAID does not protect against",
  66. "## Where RAID sits in a continuity plan",
  67. "## Where this shows up in this project",
  68. "## Free path: a parity drill on your own computer",
  69. "## Optional: an array on loopback files (shown, not run)",
  70. EXERCISE,
  71. "## Build, break, detect, evade, defend (on paper)",
  72. "## Checkpoint",
  73. "## Common mistakes",
  74. "## Not verified, plainly",
  75. "## Claims register",
  76. )
  77. # ---- the formulas the exercise answers come from -----------------------------------------------------------------------
  78. def usable_tb(level: str, drives: int, size_tb: float) -> float:
  79. return {"RAID 0": drives * size_tb, "RAID 10": drives // 2 * size_tb, "RAID 5": (drives - 1) * size_tb, "RAID 6": (drives - 2) * size_tb}[level]
  80. def survive_for_certain(level: str, drives: int) -> int:
  81. return {"RAID 0": 0, "RAID 10": 1, "RAID 5": 1, "RAID 6": 2}[level]
  82. def survive_best_case(level: str, drives: int) -> int:
  83. return {"RAID 0": 0, "RAID 10": drives // 2, "RAID 5": 1, "RAID 6": 2}[level]
  84. def small_write_ios(level: str) -> int:
  85. """Disk operations for one small write: 1 write; 2 writes to two copies; RAID 5 reads old data and old parity and writes both;
  86. RAID 6 does the same with two parities (derived, not in the sources read)."""
  87. return {"RAID 0": 1, "RAID 10": 2, "RAID 5": 4, "RAID 6": 6}[level]
  88. def random_writes_per_second(level: str, drives: int, per_drive: int) -> float:
  89. return drives * per_drive / small_write_ios(level)
  90. def mttf_raid_hours(mttf_disk: float, data_disks: int, group: int, check_per_group: int, mttr: float) -> float:
  91. """Patterson, Gibson and Katz (1987): MTTF_RAID = MTTF_disk^2 / ((D + C * nG) * (G + C - 1) * MTTR)."""
  92. groups = data_disks / group
  93. return mttf_disk**2 / ((data_disks + check_per_group * groups) * (group + check_per_group - 1) * mttr)
  94. def afr_from_drive_days(failures: int, drive_days: int) -> float:
  95. return failures / (drive_days / 365)
  96. def chance_any_fails(afr: float, drives: int) -> float:
  97. return 1 - (1 - afr) ** drives
  98. def chance_of_one_or_more_ure(bits_read: float, rate_per_bit: float) -> float:
  99. return 1 - math.exp(-bits_read * rate_per_bit)
  100. def rebuild_hours(size_tb: float, mb_per_second: float) -> float:
  101. return size_tb * 1e12 / (mb_per_second * 1e6) / 3600
  102. def xor_bytes(*blocks: bytes) -> bytes:
  103. out = bytearray(len(blocks[0]))
  104. for block in blocks:
  105. for i, b in enumerate(block):
  106. out[i] ^= b
  107. return bytes(out)
  108. # ---- helpers on the page -----------------------------------------------------------------------------------------------
  109. def text() -> str:
  110. return PAGE.read_text(encoding="utf-8")
  111. def slug(heading: str) -> str:
  112. return re.sub(r"[^a-z0-9-]", "", re.sub(r"[^a-z0-9 -]", "", heading.lower()).strip().replace(" ", "-"))
  113. def headings(body: str) -> set[str]:
  114. return {slug(h) for h in re.findall(r"^#+ (.+)$", body, re.MULTILINE)}
  115. def section(body: str, heading: str) -> str:
  116. return body.split(f"\n{heading}\n")[1].split("\n## ")[0]
  117. def table_rows(block: str) -> list[list[str]]:
  118. rows = [line for line in block.splitlines() if line.startswith("|") and not line.startswith("|---")]
  119. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  120. def register_rows(body: str) -> list[list[str]]:
  121. return table_rows(body.split("## Claims register")[1])
  122. def rows_missing_status(rows: list[list[str]]) -> list[str]:
  123. return [r[0] for r in rows if not any(w in r[-1] for w in STATUS_WORDS)]
  124. def sourced_rows_without_url_and_date(rows: list[list[str]]) -> list[str]:
  125. exempt = ("The maintainer's framing", "General knowledge", "Derived by the author", "The author's own", "Constructed by the author")
  126. bad = []
  127. for row in rows:
  128. if row[1].startswith(exempt):
  129. continue
  130. if not URL.search(row[1]) or DATE not in row[2]:
  131. bad.append(row[0])
  132. return bad
  133. def british_words(body: str) -> list[str]:
  134. return sorted(w for w in BRITISH if re.search(rf"\b{w}\b", body))
  135. def vendor_names(body: str) -> list[str]:
  136. low = body.lower()
  137. return [v for v in VENDORS if re.search(rf"\b{re.escape(v)}\b", low)]
  138. def png_size(path: Path) -> tuple[int, int]:
  139. data = path.read_bytes()
  140. assert data[:8] == b"\x89PNG\r\n\x1a\n", path
  141. return struct.unpack(">II", data[16:24])
  142. def too_tall(width: int, height: int) -> bool:
  143. return height > 1.6 * width
  144. POSTURE = (
  145. r"required_approving_review_count",
  146. r"required approving review",
  147. r"enforce_admins",
  148. r"branch protection",
  149. r"branch rule",
  150. r"stale reviews",
  151. r"no human approval",
  152. r"github api",
  153. r"gh api",
  154. )
  155. def posture_phrases(body: str) -> list[str]:
  156. """Statements of this repository's own security settings must not be published."""
  157. return [p for p in POSTURE if re.search(p, body, re.IGNORECASE)]
  158. # ---- the page ----------------------------------------------------------------------------------------------------------
  159. def test_the_banner_says_it_was_written_from_reading_and_names_what_was_not_run():
  160. body = text()
  161. assert body.startswith("# RAID: levels, parity, rebuilds, and why it is continuity and not a backup")
  162. assert "Status: unverified draft" in body
  163. assert "**Not run:**" in body and "**Not read:**" in body and DATE in body
  164. assert "issue 421" in body
  165. assert "defensive and educational" in body.lower()
  166. def test_the_page_leads_with_continuity_and_not_a_backup_and_every_topic_has_a_section():
  167. body = text()
  168. opening = body.split("> Unfamiliar word or acronym?")[0]
  169. assert "business continuity" in opening and "not a backup" in opening
  170. assert "RAID is not a backup" in body
  171. missing = [t for t in TOPICS if f"\n{t}\n" not in body]
  172. assert not missing, missing
  173. assert body.index(FRAMING) < body.index("## The words: striping"), "the framing comes before the mechanics"
  174. assert body.index("## What you will be able to do") < body.index(FRAMING)
  175. abilities = section(body, "## What you will be able to do")
  176. assert "not a backup" in abilities
  177. def test_the_framing_section_has_the_sources_the_maintainer_framing_rests_on():
  178. sec = section(text(), FRAMING)
  179. for needed in (
  180. "availability",
  181. "business continuity",
  182. "at most one copy",
  183. "SP 800-34",
  184. "cannot be a replacement for a solid backup strategy",
  185. "backup, backup, BACK UP",
  186. "RAID is not a panacea",
  187. "Patterson, Gibson and Katz",
  188. "backup versions of all information every night",
  189. "independent",
  190. ):
  191. assert needed in sec, needed
  192. for link in (BCP, CIA, BACKUPS, DEEP):
  193. assert f"]({link}.md" in sec, link
  194. def test_the_event_table_says_what_raid_survives_and_what_a_backup_survives():
  195. sec = section(text(), FRAMING)
  196. rows = table_rows(sec)
  197. assert len(rows) >= 9, "the guard collected too few rows"
  198. events = " ".join(r[0] for r in rows).lower()
  199. for needed in ("drive", "deleted", "ransomware", "corrupt", "controller", "fire", "theft", "second drive", "power"):
  200. assert needed in events, needed
  201. assert "Yes" in rows[0][1] and "drive" in rows[0][0].lower()
  202. no_raid = sum("**No**" in r[1] for r in rows)
  203. no_backup = sum("**No**" in r[2] for r in rows)
  204. assert no_raid >= 6, no_raid
  205. assert no_backup <= 2, "a backup is not a cure for everything either, but the table must not say so for most rows"
  206. assert any("not" in r[2].lower() or "only if" in r[2].lower() for r in rows), "the backup column has its own conditions"
  207. assert not [r[0] for r in rows if len(r) != 3]
  208. def test_the_event_table_guard_bites():
  209. rows = table_rows("| Event | RAID | Backup |\n|---|---|---|\n| a drive fails | Yes | Yes |\n| ransomware | Yes | Yes |\n")
  210. assert sum("**No**" in r[1] for r in rows) == 0
  211. def test_every_linked_wiki_page_exists_and_every_anchor_is_a_real_heading():
  212. found = LINK.findall(text())
  213. assert len({t for t, _ in found}) >= 8, "the guard collected too few links"
  214. missing = sorted({t for t, _ in found if not (WIKI / f"{t}.md").exists()})
  215. assert not missing, missing
  216. bad = [f"{t}#{a}" for t, a in found if a and a not in headings((WIKI / f"{t}.md").read_text(encoding="utf-8"))]
  217. assert not bad, bad
  218. linked = {t for t, _ in found}
  219. for needed in (BCP, CIA, BACKUPS, DEEP, "Glossary", "Hashing-Encryption-and-Keys", "Terminal-and-Your-First-Script"):
  220. assert needed in linked, needed
  221. def test_the_blast_radius_lesson_is_named_in_plain_text_so_its_link_cap_holds():
  222. body = text()
  223. assert "Plan-for-Failure-Blast-Radius" not in body
  224. def test_the_lesson_is_registered_in_nav_contents_reading_order_and_sidebar():
  225. nav = nav_text(WIKI)
  226. line = next(row for row in nav.splitlines() if f"page: {NAME}," in row)
  227. assert 'status: "draft"' in line and 'subgroup: "Continuity, backups and recovery"' in line
  228. for special in ("Contents.md", "Reading-Order.md", "_Sidebar.md"):
  229. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  230. def test_the_backups_deep_dive_links_this_lesson_and_this_lesson_links_it_back():
  231. assert f"]({NAME}.md" in (WIKI / f"{DEEP}.md").read_text(encoding="utf-8")
  232. assert f"]({DEEP}.md" in text()
  233. def test_glossary_rows_point_at_real_headings_and_none_repeats_a_term():
  234. heads = headings(text())
  235. anchors = set()
  236. rows = 0
  237. glossary = glossary_text(WIKI)
  238. for line in glossary.splitlines():
  239. if f"{NAME}.md" in line:
  240. rows += 1
  241. anchors.update(re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line))
  242. assert rows >= 11, "expected glossary rows for the new terms"
  243. assert anchors and anchors <= heads, sorted(anchors - heads)
  244. terms = [m.group(1).lower() for m in re.finditer(r"^\| \*\*([^*]+)\*\* \|", glossary, re.MULTILINE)]
  245. assert len(terms) > 100, "the guard collected too few glossary terms"
  246. mine = [m.group(1).lower() for m in re.finditer(rf"^\| \*\*([^*]+)\*\* \|[^\n]*{NAME}\.md", glossary, re.MULTILINE)]
  247. assert len(mine) == rows, (len(mine), rows)
  248. repeated = sorted({t for t in mine if terms.count(t) > 1})
  249. assert not repeated, repeated
  250. for term in ("raid", "striping", "mirroring", "parity", "hot spare", "degraded array", "write hole"):
  251. assert any(t.startswith(term) for t in mine), term
  252. assert sorted({t for t in ["a", "b", "a"] if ["a", "b", "a"].count(t) > 1}) == ["a"], "the repeat guard bites"
  253. def test_american_spelling_no_em_dashes_no_addresses_and_no_vendor_names_outside_the_register():
  254. body = text()
  255. low = body.lower()
  256. assert "—" not in body
  257. assert not IPV4.findall(body), IPV4.findall(body)
  258. assert not british_words(low), british_words(low)
  259. prose = body.split("## Claims register")[0]
  260. assert not vendor_names(prose), vendor_names(prose)
  261. assert "raid" in low, "the guard collected nothing"
  262. for banned in ("most reliable brand", "best brand", "we recommend buying", "buy the"):
  263. assert banned not in low, banned
  264. def test_the_spelling_and_vendor_guards_bite():
  265. assert british_words("the organisation's defence and an offence") == ["defence", "offence", "organisation"]
  266. assert not british_words("the organization's defense and impact analyses")
  267. assert vendor_names("Seagate and WD Red drives") == ["seagate", "wd red"]
  268. assert not vendor_names("a NAS line sold for arrays")
  269. def test_every_table_has_a_named_first_header_cell():
  270. bad = []
  271. lines = text().splitlines()
  272. tables = 0
  273. for i, line in enumerate(lines[:-1]):
  274. if line.startswith("|") and lines[i + 1].startswith("|---") and (i == 0 or not lines[i - 1].startswith("|")):
  275. tables += 1
  276. if not line.strip("|").split("|")[0].strip():
  277. bad.append(i + 1)
  278. assert tables >= 8, "the guard collected too few tables"
  279. assert not bad, bad
  280. def test_no_security_posture_detail_of_this_repository_is_on_the_page_and_the_guard_bites():
  281. body = text()
  282. assert "raid" in body.lower(), "the guard collected nothing"
  283. assert not posture_phrases(body), posture_phrases(body)
  284. assert posture_phrases("check the branch protection settings")
  285. assert not posture_phrases("check the settings in your own system")
  286. # ---- diagrams ----------------------------------------------------------------------------------------------------------
  287. def test_every_diagram_has_alt_text_a_source_a_picture_and_a_wide_shape():
  288. body = text()
  289. found = list(WRAPPED.finditer(body))
  290. assert len(found) == 3, "expected three diagrams"
  291. assert len(re.findall(r"```mermaid", body)) == len(found), "a Mermaid block has no picture above it"
  292. manifest = json.loads((ROOT / "docs" / "diagrams.json").read_text())
  293. for m in found:
  294. alt = m["alt"].strip()
  295. assert 20 <= len(alt) <= 150, alt
  296. png = (PAGE.parent / m["path"]).resolve()
  297. assert png.is_file(), m["path"]
  298. assert png.relative_to(ROOT).as_posix() in manifest, m["path"]
  299. assert m["src"].lstrip().startswith("flowchart LR"), m["path"]
  300. width, height = png_size(png)
  301. assert not too_tall(width, height), (m["path"], width, height)
  302. def test_the_diagram_guards_bite():
  303. bare = "![alt text here](images/x.png)\n\nno details block, so no source\n"
  304. assert not WRAPPED.search(bare)
  305. good = "![alt text here](images/x.png)\n\n<details>\n<summary>Diagram source (Mermaid)</summary>\n\n```mermaid\nflowchart LR\n a --> b\n```\n\n</details>"
  306. assert WRAPPED.search(good)
  307. assert not WRAPPED.search(good.replace("<details>\n", ""))
  308. assert too_tall(100, 161) and not too_tall(100, 160)
  309. def test_the_diagrams_cover_what_raid_survives_the_layouts_and_the_risk_window():
  310. found = list(WRAPPED.finditer(text()))
  311. alts = " ".join(m["alt"].lower() for m in found)
  312. for topic in ("backup", "level", "rebuild"):
  313. assert topic in alts, topic
  314. sources = " ".join(m["src"] for m in found)
  315. for needed in ("RAID 0", "RAID 1", "RAID 5", "RAID 6", "RAID 10", "degraded", "ransomware", "deleted"):
  316. assert needed in sources, needed
  317. # ---- the register ------------------------------------------------------------------------------------------------------
  318. def test_every_claims_register_row_has_a_status_a_url_and_the_read_date():
  319. rows = register_rows(text())
  320. assert len(rows) >= 18, "the guard collected too few rows"
  321. assert not rows_missing_status(rows)
  322. assert not sourced_rows_without_url_and_date(rows)
  323. joined = " ".join(r[1] for r in rows)
  324. for host in (
  325. "www2.eecs.berkeley.edu/Pubs/TechRpts/1987/CSD-87-391.pdf",
  326. "nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-34r1.pdf",
  327. "raid.wiki.kernel.org/index.php/How_to_protect_your_data",
  328. "raid.wiki.kernel.org/index.php/Scrubbing_the_drives",
  329. "raid.wiki.kernel.org/index.php/Timeout_Mismatch",
  330. "raid.wiki.kernel.org/",
  331. "docs.kernel.org/admin-guide/md.html",
  332. "docs.kernel.org/driver-api/md/raid5-ppl.html",
  333. "docs.kernel.org/driver-api/md/raid5-cache.html",
  334. "man7.org/linux/man-pages/man8/mdadm.8.html",
  335. "man7.org/linux/man-pages/man8/losetup.8.html",
  336. "openzfs.github.io/openzfs-docs/Basic%20Concepts/Pool%20Structure/RAIDZ.html",
  337. "openzfs.github.io/openzfs-docs/man/master/8/zpool-scrub.8.html",
  338. "learn.microsoft.com/en-us/windows-server/storage/storage-spaces/fault-tolerance",
  339. "backblaze.com/cloud-storage/resources/hard-drive-test-data",
  340. ):
  341. assert host in joined, host
  342. assert sum(DATE in r[2] for r in rows) >= 14
  343. def test_the_register_guards_bite():
  344. assert rows_missing_status([["X", "y", "maybe"]]) == ["X"]
  345. assert sourced_rows_without_url_and_date([["X", "[p](https://example.com/p)", "Read 2026-10-31"]]) == ["X"]
  346. assert sourced_rows_without_url_and_date([["X", "a page", "Read 2026-11-01"]]) == ["X"]
  347. assert not sourced_rows_without_url_and_date([["X", "General knowledge", "est."]])
  348. # ---- facts that can be checked on the page -----------------------------------------------------------------------------
  349. def test_the_levels_table_matches_the_formulas():
  350. sec = section(text(), "## The levels, side by side")
  351. rows = table_rows(sec)
  352. names = [r[0] for r in rows]
  353. assert len(rows) >= 6, "the guard collected too few rows"
  354. for needed in ("RAID 0", "RAID 1", "RAID 5", "RAID 6", "RAID 10", "RAIDZ"):
  355. assert any(n.startswith(needed) for n in names), needed
  356. by = {r[0].split(" (")[0]: r for r in rows}
  357. assert "(n - 1)" in by["RAID 5"][2] and "(n - 2)" in by["RAID 6"][2]
  358. assert "n / 2" in by["RAID 10"][2] and "all n" in by["RAID 0"][2]
  359. assert "one" in by["RAID 5"][3].lower() and "two" in by["RAID 6"][3].lower() and "none" in by["RAID 0"][3].lower()
  360. assert "Not a backup" in sec or "not a backup" in sec
  361. def test_the_exercise_capacity_table_is_computed_here_and_matches_the_page():
  362. ex = section(text(), EXERCISE)
  363. cap = [r for r in table_rows(ex) if r[0].startswith("RAID") and len(r) == 7]
  364. assert [r[0].split(" (")[0] for r in cap] == ["RAID 0", "RAID 10", "RAID 5", "RAID 6"], [r[0] for r in cap]
  365. drives, size = 6, 8
  366. for r in cap:
  367. level = r[0].split(" (")[0]
  368. assert int(r[1]) == drives
  369. assert int(r[2]) == usable_tb(level, drives, size), level
  370. assert r[3] == f"{usable_tb(level, drives, size) / (drives * size):.0%}", level
  371. assert int(r[4]) == survive_for_certain(level, drives), level
  372. assert int(r[5]) == survive_best_case(level, drives), level
  373. assert int(r[6]) == small_write_ios(level), level
  374. def test_the_exercise_write_table_is_computed_here_and_matches_the_page():
  375. ex = section(text(), EXERCISE)
  376. rows = [r for r in table_rows(ex) if r[0].startswith("RAID") and len(r) == 2]
  377. assert [r[0].split(" (")[0] for r in rows] == ["RAID 0", "RAID 10", "RAID 5", "RAID 6"]
  378. for r in rows:
  379. level = r[0].split(" (")[0]
  380. assert float(r[1].replace(",", "")) == random_writes_per_second(level, 6, 150), level
  381. assert "150" in ex and "est." in ex
  382. def test_the_exercise_reliability_figures_are_the_ones_the_formulas_give():
  383. ex = section(text(), EXERCISE)
  384. one_group = mttf_raid_hours(30_000, 100, 10, 1, 1)
  385. wide = mttf_raid_hours(30_000, 100, 25, 1, 1)
  386. day = mttf_raid_hours(30_000, 100, 10, 1, 24)
  387. assert round(one_group) == 818_182 and round(wide) == 346_154 and round(day) == 34_091
  388. for needed in (
  389. f"{one_group:,.0f} hours",
  390. f"{one_group / 8760:.1f} years",
  391. f"{wide:,.0f} hours",
  392. f"{day:,.0f} hours",
  393. f"{day / 8760:.1f} years",
  394. "820,000",
  395. "346,000",
  396. ):
  397. assert needed in ex, needed
  398. # The paper's own table agrees with the formula to the figure it prints.
  399. assert abs(one_group - 820_000) / 820_000 < 0.005 and abs(wide - 346_000) / 346_000 < 0.005
  400. assert mttf_raid_hours(30_000, 100, 10, 1, 24) < mttf_raid_hours(30_000, 100, 10, 1, 1) / 20, "a slower repair costs most of the margin"
  401. def test_the_exercise_failure_rate_and_rebuild_figures_are_computed_here():
  402. ex = section(text(), EXERCISE)
  403. afr = afr_from_drive_days(1_498, 31_553_350)
  404. assert f"{afr:.2%}" == "1.73%"
  405. assert "1,498" in ex and "31,553,350" in ex and "1.73%" in ex
  406. year = chance_any_fails(0.0173, 6)
  407. assert f"{year:.1%}" in ex, f"{year:.1%}"
  408. bits = 5 * 8e12 * 8
  409. assert bits == 3.2e14
  410. pessimistic = chance_of_one_or_more_ure(bits, 1e-14)
  411. better = chance_of_one_or_more_ure(bits, 1e-15)
  412. assert f"{pessimistic:.0%}" in ex and f"{better:.0%}" in ex, (f"{pessimistic:.0%}", f"{better:.0%}")
  413. assert f"{rebuild_hours(8, 150):.1f} hours" in ex and f"{rebuild_hours(8, 50):.1f} hours" in ex
  414. assert "3.2" in ex and "1 in 10^14" in ex and "1 in 10^15" in ex
  415. assert "I did not read" in ex or "not read" in ex.lower()
  416. def test_the_formula_guards_bite():
  417. assert usable_tb("RAID 5", 6, 8) != 6 * 8
  418. assert usable_tb("RAID 5", 6, 8) == 40 and usable_tb("RAID 6", 6, 8) == 32 and usable_tb("RAID 10", 6, 8) == 24
  419. assert survive_best_case("RAID 10", 6) == 3 and survive_for_certain("RAID 10", 6) == 1
  420. assert random_writes_per_second("RAID 5", 6, 150) == 225
  421. assert mttf_raid_hours(30_000, 100, 10, 1, 2) != mttf_raid_hours(30_000, 100, 10, 1, 1)
  422. assert round(afr_from_drive_days(1_498, 31_553_350), 4) == 0.0173
  423. assert chance_of_one_or_more_ure(3.2e14, 1e-14) > chance_of_one_or_more_ure(3.2e14, 1e-15)
  424. assert round(rebuild_hours(8, 150), 1) == 14.8
  425. def test_the_exercise_is_synthetic_and_says_so_and_the_answers_say_what_they_do_not_show():
  426. ex = section(text(), EXERCISE)
  427. assert "made-up" in ex and "Example Shelf" in ex
  428. assert "independent" in ex and "correlated" in ex
  429. assert "Not run" in ex or "not run" in ex
  430. assert "worst case" in ex or "maximum" in ex
  431. # ---- the drill ---------------------------------------------------------------------------------------------------------
  432. def script() -> str:
  433. found = [textwrap.dedent(b) for t, b in FENCE.findall(text()) if t == "python" and "# raid_drill.py - " in b]
  434. assert len(found) == 1, f"expected one raid_drill.py block, found {len(found)}"
  435. return found[0]
  436. def test_the_drill_runs_and_its_output_matches_the_page(tmp_path):
  437. path = tmp_path / "raid_drill.py"
  438. path.write_text(script())
  439. done = subprocess.run(
  440. [sys.executable, "-I", str(path)],
  441. capture_output=True,
  442. text=True,
  443. timeout=60,
  444. check=False,
  445. cwd=tmp_path,
  446. env={"TMPDIR": str(tmp_path), "PATH": "/usr/bin:/bin"},
  447. )
  448. assert done.returncode == 0, done.stderr
  449. shown = next(b for t, b in FENCE.findall(text()) if t == "text" and b.startswith("== Parity"))
  450. got = [line.rstrip() for line in done.stdout.strip().splitlines()]
  451. want = [line.rstrip() for line in shown.strip().splitlines()]
  452. assert got == want
  453. assert not [p for p in tmp_path.iterdir() if p.name.startswith("raid-drill-")], "the script must delete its own lab folder"
  454. def test_the_drill_results_agree_with_an_independent_xor():
  455. a, b, c = (bytes((i * k + 7) % 256 for i in range(16)) for k in (3, 5, 11))
  456. parity = xor_bytes(a, b, c)
  457. assert xor_bytes(a, c, parity) == b, "the lost drive comes back from the others and the parity"
  458. new_a = bytes((x + 1) % 256 for x in a)
  459. new_parity = xor_bytes(xor_bytes(a, new_a), parity)
  460. assert new_parity == xor_bytes(new_a, b, c), "the small-write rule: new parity = (old data xor new data) xor old parity"
  461. stale = xor_bytes(new_a, b, parity)
  462. assert stale != c, "a stale parity rebuilds the wrong data"
  463. DRILL_BANNED = ("subprocess", "os.system", "sudo", "/dev/", "socket", "urllib", "requests", "os.remove", "shutil.move", "..\\")
  464. def drill_problems(body: str) -> list[str]:
  465. found = [b for b in DRILL_BANNED if b in body]
  466. if re.search(r"open\(\s*[\"']/", body):
  467. found.append("an absolute path is opened")
  468. return found
  469. def test_the_drill_never_touches_anything_outside_its_own_folder():
  470. body = script()
  471. assert "tempfile.mkdtemp" in body and "shutil.rmtree(lab)" in body and "finally:" in body
  472. assert not drill_problems(body), drill_problems(body)
  473. assert body.count("rmtree") == 1
  474. def test_the_drill_guard_bites():
  475. assert drill_problems('open("/etc/passwd")') == ["an absolute path is opened"]
  476. assert drill_problems("import subprocess") == ["subprocess"]
  477. assert drill_problems("path = '/dev/sda'") == ["/dev/"]
  478. assert not drill_problems("(lab / 'drive1.bin').write_bytes(data)")
  479. def test_the_drill_output_says_the_things_the_lesson_claims():
  480. shown = next(b for t, b in FENCE.findall(text()) if t == "text" and b.startswith("== Parity"))
  481. for needed in ("rebuilt drive 2 matches the original: True", "rebuilt drive 3 matches the original: False", "silent", "mirror", "backup"):
  482. assert needed in shown, needed
  483. # ---- the optional loopback block: shown, never run ---------------------------------------------------------------------
  484. ALLOWED_DEVICE = re.compile(r"^/dev/(?:md/lab|loop<[A-D]>)$")
  485. def mdadm_block() -> str:
  486. found = [b for t, b in FENCE.findall(text()) if t == "bash" and "mdadm" in b]
  487. assert len(found) == 1, f"expected one mdadm block, found {len(found)}"
  488. return found[0]
  489. def device_problems(block: str) -> list[str]:
  490. return [d for d in re.findall(r"/dev/[A-Za-z0-9_/<>-]+", block) if not ALLOWED_DEVICE.match(d)]
  491. def test_the_loopback_block_is_marked_not_run_and_names_only_the_readers_own_files():
  492. block = mdadm_block()
  493. assert block.lstrip().startswith("# NOT RUN"), "the block says it was not run on its first line"
  494. assert not device_problems(block), device_problems(block)
  495. for needed in ("truncate -s", "losetup --find --show", "mdadm --create", "--level=5", "--fail", "--remove", "--add", "--stop", "losetup -d", "--zero-superblock"):
  496. assert needed in block, needed
  497. assert block.index("--stop") < block.index("losetup -d"), "the array is stopped before the loop devices are released"
  498. prose = text().split("## Optional: an array on loopback files")[1].split("\n## ")[0]
  499. assert "Not run" in prose and "root" in prose and "only on files you made" in prose
  500. assert "mdadm --create" in prose and "existing array" in prose, "the warning about --create on an existing array is there"
  501. def test_the_loopback_guard_bites():
  502. assert device_problems("mdadm --create /dev/md/lab /dev/sda1 /dev/loop<A>") == ["/dev/sda1"]
  503. assert device_problems("mdadm --detail /dev/nvme0n1") == ["/dev/nvme0n1"]
  504. assert not device_problems("mdadm --create /dev/md/lab /dev/loop<A> /dev/loop<B>")
  505. # ---- the rest ----------------------------------------------------------------------------------------------------------
  506. def test_the_project_table_cites_existing_files_or_says_none():
  507. sec = section(text(), "## Where this shows up in this project")
  508. rows = table_rows(sec)
  509. assert len(rows) >= 5, "the guard collected too few rows"
  510. for r in rows:
  511. paths = re.findall(r"`((?:modules|stacks|scripts|docs|\.github|tests)/[A-Za-z0-9_./-]+)`", r[2])
  512. assert all((ROOT / p).exists() for p in paths), r[0]
  513. assert paths or r[2].startswith("None"), r[0]
  514. assert sum(r[2].startswith("None") for r in rows) >= 2
  515. assert "no RAID" in sec or "no word RAID" in sec
  516. def test_what_the_page_did_not_read_is_named():
  517. part = section(text(), "## Not verified, plainly")
  518. for needed in (
  519. "datasheet",
  520. "hardware RAID",
  521. "ZFS",
  522. "Storage Spaces",
  523. "mdadm --create",
  524. "RAID 2",
  525. "Not run",
  526. "SNIA",
  527. "Backblaze",
  528. "level 3",
  529. ):
  530. assert needed in part, needed
  531. def test_the_drill_and_exercise_say_run_or_not_run_for_every_command_block():
  532. body = text()
  533. blocks = [(t, b) for t, b in FENCE.findall(body) if t in ("bash", "python")]
  534. assert len(blocks) >= 3, "the guard collected too few code blocks"
  535. for t, b in blocks:
  536. first = b.lstrip().splitlines()[0]
  537. assert first.startswith(("# NOT RUN", "#!/usr/bin/env python3", "python3 -I raid_drill.py")), first
  538. assert "**Observed**" in body or "Observed" in body.split("## Claims register")[1]