Files
materials/.sre-s23/gen.js
huanghaosheng b12ac67cfd feat: 阶段 4(云原生与平台工程)与阶段 5(故障处理与工程文化)详解上线
新增 10 个模块、130 章 / 416 小节、约 65.7 万字,全站 203 → 343 页。
目录页阶段 0–5 全部显示「详解已上线」,仅阶段 6 待补。

阶段 4 · 上规模(s4-01 … s4-05)
- Kubernetes 核心:五组件与调谐循环、工作负载选型、Service / Ingress / CNI / DNS、
  PV / PVC / StorageClass、ConfigMap 热更新陷阱、三探针自伤配置、QoS 与驱逐顺序、
  HPA / VPA / Cluster Autoscaler、五类异常排障路径、版本升级与 etcd 恢复
- GitOps 与声明式交付:Kustomize base/overlay、Helm values 优先级、Argo CD 同步机制、
  漂移检测与自动纠偏、多环境差异收敛、密钥外置、Argo Rollouts / Flagger 金丝雀、
  对象归属与三层边界
- 基础设施即代码:state 与加锁、module 化拆分、plan 评审与 CI 审批、漂移治理、
  Ansible 幂等与 --check、Packer 不可变镜像、OIDC 与标签治理、四类反模式
- 服务网格与网关:mTLS 与证书轮换、流量切分、重试预算与熔断、遥测基数爆炸、
  网关选型与职责边界、多一跳延迟实测与成本、何时不上网格的判据
- 平台工程与自助化:IDP 与 Golden Path、服务脚手架、预览环境、服务目录与 CMDB、
  可复用流水线、DORA 度量、推广阻力、四级演进路线

阶段 5 · 扛得住(s5-01 … s5-05)
- On-call 与应急响应:轮转与升级路径、交接班清单、IC / CL / OL、P0–P3 定级、
  先止血后根因、六种止血手段、沟通节奏、Runbook、告警疲劳、演练
- 复盘与根因分析:时间线三层分离、5 Whys 与故障树、无指责文化、贡献因素、
  行动项闭环、六类高频根因、模板与完整案例、复盘会、质量指标
- 性能分析与内核调优:六大命令各自回答什么、CPU / 内存 / IO 分析、perf 与火焰图、
  bcc / bpftrace 与 off-CPU、内核与协议参数、GC / 连接池 / 锁竞争、
  五层推理链与定位报告
- 安全与合规运维:最小权限与堡垒机、密钥轮换与吊销、审计日志、
  供应链签名 / SBOM / 扫描门禁、漏洞分级 SLA、六阶段应急响应与取证顺序、
  CIS 基线、暴露面收敛、等保落地
- 效率与 Toil 消除:Toil 五判据、记账口径、占比目标、评分与回收期、自动化与自助化、
  知识沉淀、可运维性评审与门禁、SLO 谈判、改进收益度量

脚手架 .sre-s23
- gen.js:CHAIN 扩到 25 个模块,STAGE_TITLE 补 s5 / s6,nextStage 去掉硬编码
- SPEC.md:读者画像上调到「已搭起指标 / 日志 / 追踪与 SLO 体系」,新增第 6 节逐条
  列出 10 个模块必须覆盖的知识点
- coverage.js:关键词表扩到 18 个模块,缺目录时跳过而非抛错
- 新增 metrics.js(统计各模块章节 / 小节 / 千字)与 check-pages-table.js
  (校验 PAGES 路由表无死链、统计各阶段上线进度)

内容修复:模板字面量逃逸(29 处)
- s4-05-platform 2 处 \"、s5-03-perf 7 处行尾 \、s5-04-security 4 处行尾 \:本次扫描发现并修复
- s4-02-gitops 16 处(6 处 \" + 10 处行尾 \):扫描发现,作者在最终保存前自行修复
- 其中 3 个模块的作者自查结论为「残留 0 处」,与实测不符,故把 fix-esc 定为必跑步骤
- 损坏表现为生成的 HTML 里多行命令粘成一行、内层引号丢失(如
  yq "select(.kind==\"Deployment\")" 变成 yq "select(.kind=="Deployment")"),
  HTML 结构校验查不出来,只能靠源码扫描 + 渲染结果比对

校验结果
- check-pages:OK 全部校验通过(共 343 个页面)
- check-pre:OK 所有 JSON 代码块均可解析
- verify-template:OK 新页面只使用既有样式(50–53 种 class,基线 54)
- coverage:OK 全部知识点关键词均已覆盖
- check-pages-table:25 条路由,0 条死链
- fix-esc:10 个模块残留反斜杠均为 0
- 模块间 pager 链路核对:s3-04-chaos → s4-01 → … → s5-05-toil → 阶段 6

其他
- 站点 README:目录树补 10 个模块、内容表新增 10 行、「其余阶段(4–6)」改为「(6)」
- s3-04-chaos 目录页 pager 指向 s4-01-k8s;侧栏目录树全站重建
2026-10-08 18:19:34 +08:00

383 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/* ==========================================================================
阶段 2 / 3 内容生成器(临时构建工具,全部生成完成并校验通过后可删除)
用法:
node .sre-s23/gen.js --all 生成 content/ 下全部模块
node .sre-s23/gen.js --only <dir> 只生成一个模块
node .sre-s23/gen.js --check <dir> 只校验不写文件
内容源:.sre-s23/content/<dir>.js
module.exports = {
dir, title, sub, no, total,
stage: { num: 2, title: "看得见" },
lead: `...HTML...`,
chapters: [ { file:"01-why", id:"why", title:"...", html:`...` } ]
}
生成物:
knowledge/sre-learning-path/modules/<dir>/index.html
knowledge/sre-learning-path/modules/<dir>/NN-<slug>.html
侧栏目录树留空,由 tools/build-nav.js 统一填充。
========================================================================== */
const fs = require("fs");
const path = require("path");
const SITE = path.resolve(__dirname, "..", "knowledge", "sre-learning-path");
const CONTENT = path.join(__dirname, "content");
/* 完整模块链条:用于生成「上一模块 / 下一模块」 */
const CHAIN = [
["s0-01-linux", "Linux 系统与命令行", "s0"],
["s0-02-network", "计算机网络", "s0"],
["s0-03-programming", "编程与自动化基础", "s0"],
["s1-01-nginx", "Nginx 与流量入口", "s1"],
["s1-02-deploy", "应用部署与发布", "s1"],
["s1-03-container", "容器与镜像", "s1"],
["s1-04-cicd", "CI/CD 流水线", "s1"],
["s2-01-metrics", "指标与 Prometheus", "s2"],
["s2-02-logs", "日志采集与检索", "s2"],
["s2-03-trace", "链路追踪", "s2"],
["s2-04-dashboard", "看板与可视化", "s2"],
["s3-01-slo", "SLI / SLO / 错误预算", "s3"],
["s3-02-ha", "高可用与容灾", "s3"],
["s3-03-capacity", "容量规划与成本", "s3"],
["s3-04-chaos", "混沌工程与演练", "s3"],
["s4-01-k8s", "Kubernetes 核心", "s4"],
["s4-02-gitops", "GitOps 与声明式交付", "s4"],
["s4-03-iac", "基础设施即代码", "s4"],
["s4-04-mesh", "服务网格与网关", "s4"],
["s4-05-platform", "平台工程与自助化", "s4"],
["s5-01-oncall", "On-call 与应急响应", "s5"],
["s5-02-postmortem", "复盘与根因分析", "s5"],
["s5-03-perf", "性能分析与内核调优", "s5"],
["s5-04-security", "安全与合规运维", "s5"],
["s5-05-toil", "效率与 Toil 消除", "s5"]
];
const STAGE_TITLE = {
s0: "打地基", s1: "服务上线", s2: "看得见",
s3: "稳得住", s4: "上规模", s5: "扛得住", s6: "成熟"
};
/* ---------------------------------------------------------------- 工具 */
const esc = s => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;")
.replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const stripTags = s => s.replace(/<[^>]+>/g, "");
const decode = s => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">")
.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, " ")
.replace(/&mdash;/g, "—").replace(/&amp;/g, "&");
const plain = s => decode(stripTags(s)).replace(/\s+/g, " ").trim();
const stripNo = s => s.replace(/^\s*\d+(?:\.\d+)*\s*[\.、]?\s*/, "").trim();
const textLen = s => stripTags(s).replace(/\s+/g, "").length;
/* 统一缩进:去掉公共前导空白,再按 pad 重排 */
function reindent(html, pad) {
const lines = String(html).replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "").split("\n");
const indents = lines.filter(l => l.trim()).map(l => (l.match(/^[ \t]*/) || [""])[0].length);
const min = indents.length ? Math.min(...indents) : 0;
return lines.map(l => (l.trim() ? pad + l.slice(min) : "")).join("\n");
}
/* ---------------------------------------------------------------- 校验 */
const LENIENT = process.argv.includes("--lenient"); // 冒烟测试用:跳过字数下限
const problems = [];
const fail = m => problems.push(m);
function validate(mod, srcName) {
const need = ["dir", "title", "sub", "no", "total", "stage", "lead", "chapters"];
for (const k of need) if (!mod[k]) fail(`${srcName}: 缺少字段 ${k}`);
if (!mod.stage || !mod.stage.num || !mod.stage.title) fail(`${srcName}: stage 需要 {num,title}`);
if (!/^s\d-\d\d-[a-z0-9-]+$/.test(mod.dir || "")) fail(`${srcName}: dir 命名应为 sN-NN-slug`);
if (!Array.isArray(mod.chapters) || !mod.chapters.length) { fail(`${srcName}: chapters 为空`); return; }
const files = new Set();
const ids = new Set();
let total = 0;
(mod.chapters || []).forEach((c, i) => {
const tag = `${srcName} 第 ${i + 1} 章`;
if (!/^\d\d-[a-z0-9-]+$/.test(c.file || "")) fail(`${tag}: file 应为 NN-slug(小写连字符)`);
if (c.file && parseInt(c.file.slice(0, 2), 10) !== i + 1) fail(`${tag}: file 序号应为 ${String(i + 1).padStart(2, "0")}`);
if (files.has(c.file)) fail(`${tag}: file 重复 ${c.file}`);
files.add(c.file);
if (!c.title || !c.title.trim()) fail(`${tag}: 缺少 title`);
if (!/^[a-z][a-z0-9-]*$/.test(c.id || "")) fail(`${tag}: id 应为小写连字符(用于 <h2 id>)`);
if (ids.has(c.id)) fail(`${tag}: id 重复 ${c.id}`);
ids.add(c.id);
if (!c.html || (!LENIENT && textLen(c.html) < 600)) fail(`${tag}: 正文过短(${textLen(c.html || "")} 字,至少 600)`);
total += textLen(c.html || "");
/* <pre> 必须有 data-lang,且内部 < 必须转义 */
const pres = (c.html || "").match(/<pre[\s\S]*?<\/pre>/g) || [];
pres.forEach((blk, k) => {
if (!/<pre[^>]*data-lang=/.test(blk)) fail(`${tag}: 第 ${k + 1} 个 <pre> 未标注 data-lang`);
const body = blk.replace(/^<pre[^>]*>/, "").replace(/<\/pre>$/, "");
if (/</.test(body)) fail(`${tag}: 第 ${k + 1} 个 <pre> 内有未转义的 <`);
});
/* 标签配对 */
for (const t of ["div", "section", "details", "table", "ul", "ol", "li", "p", "span"]) {
const o = ((c.html || "").match(new RegExp("<" + t + "(?=[\\s>])", "g")) || []).length;
const cl = ((c.html || "").match(new RegExp("</" + t + ">", "g")) || []).length;
if (o !== cl) fail(`${tag}: <${t}> 开合不匹配 ${o}/${cl}`);
}
/* h3 必须带 id */
const h3all = ((c.html || "").match(/<h3[ >]/g) || []).length;
const h3id = ((c.html || "").match(/<h3 id="/g) || []).length;
if (h3all !== h3id) fail(`${tag}: 有 h3 未补 id(${h3id}/${h3all})`);
/* 中文正文里不出现 ASCII 单引号 */
const prose = (c.html || "").replace(/<pre[\s\S]*?<\/pre>/g, "")
.replace(/<code>[\s\S]*?<\/code>/g, "").replace(/<[^>]+>/g, "");
if (/'/.test(prose)) fail(`${tag}: 中文正文里出现 ASCII 单引号,请改用「」`);
/* 危险:正文里出现裸 < 会被浏览器吞掉 */
const bare = (c.html || "").replace(/<pre[\s\S]*?<\/pre>/g, "")
.replace(/<[a-zA-Z\/!][^>]*>/g, "");
if (/</.test(bare)) fail(`${tag}: 正文里有未转义的 <`);
});
if (!LENIENT && total < 11000) fail(`${srcName}: 全模块正文合计 ${total} 字,偏少(建议 ≥ 14000)`);
mod._total = total;
/* 必须有收尾的自测章 */
const last = (mod.chapters || [])[mod.chapters.length - 1];
if (last && !/自测|checklist/.test(last.file + last.title)) {
fail(`${srcName}: 最后一章应是「完成标准与自测」(当前 ${last.file})`);
}
return problems.length === 0;
}
/* ---------------------------------------------------------------- 模板 */
function head(title, desc) {
return `<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${esc(title)}</title>
<meta name="description" content="${esc(desc)}">
<link rel="stylesheet" href="../../assets/doc.css">
</head>
<body>
<header class="topbar">
<div class="tb-in">
<a class="brand" href="../../index.html"><span class="logo">SRE</span><div>从零到成熟<small>模块详解</small></div></a>
<div class="crumbs">
<a href="../../index.html">学习路径</a><span class="sep">/</span>
<a href="../../index.html#${mod.stageAnchor}">阶段 ${mod.stage.num} · ${esc(mod.stage.title)}</a><span class="sep">/</span>
${mod.crumbTail}
</div>
<div class="spacer"></div>
<button class="btn" id="tocToggle">☰ 导航</button>
<button class="btn" id="themeBtn" title="切换到深色主题">深色</button>
</div>
</header>
<div class="layout" id="layout">
<aside class="sidebar">
<h2>章节目录</h2>
<nav id="chapters"></nav>
<div class="side-foot">
<a class="btn" href="index.html">← 模块目录</a>
<a class="btn" href="../../index.html">学习路径</a>
</div>
</aside>
<div class="mask" id="mask"></div>
<main class="main-col">
<article>
`;
}
let mod = null;
function pager(prevHref, prevK, prevV, nextHref, nextK, nextV) {
const a = prevHref
? `<a class="prev" href="${prevHref}"><span class="k">${prevK}</span><span class="v">${esc(prevV)}</span></a>`
: `<a class="prev disabled"><span class="k">${prevK}</span><span class="v">${esc(prevV)}</span></a>`;
const b = nextHref
? `<a class="next" href="${nextHref}"><span class="k">${nextK}</span><span class="v">${esc(nextV)}</span></a>`
: `<a class="next disabled"><span class="k">${nextK}</span><span class="v">${esc(nextV)}</span></a>`;
return a + "\n " + b;
}
/* ---------------------------------------------------------------- 生成 */
function generate(m) {
mod = m;
mod.stageAnchor = m.stage.anchor || ("s" + m.stage.num);
const outDir = path.join(SITE, "modules", m.dir);
fs.mkdirSync(outDir, { recursive: true });
const idx = CHAIN.findIndex(x => x[0] === m.dir);
const prevMod = idx > 0 ? CHAIN[idx - 1] : null;
const nextMod = idx >= 0 && idx < CHAIN.length - 1 ? CHAIN[idx + 1] : null;
const nextStage = "s" + (Number(m.stage.num) + 1);
/* ---- 模块目录页 ---- */
const secTotal = m.chapters.reduce((n, c) =>
n + ((c.html.match(/<h3 id="/g) || []).length), 0);
const kilo = Math.round(m._total / 1000);
const chaplist = m.chapters.map((c, i) => {
const no = i + 1;
const secs = [...c.html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)]
.map(x => `<a href="${c.file}.html#${x[1]}">${esc(stripNo(plain(x[2])))}</a>`).join("");
return ` <li class="chap-item">
<div class="ci-head">
<span class="ci-no">${no}</span>
<a class="ci-title" href="${c.file}.html">${esc(c.title)}</a>
<a class="ci-go" href="${c.file}.html">进入 →</a>
</div>${secs ? `\n <div class="ci-secs">${secs}</div>` : ""}
</li>`;
}).join("\n");
mod.crumbTail = `<b>${esc(m.title)}</b>`;
mod.footTail = "模块目录";
const idxPrev = prevMod
? [`../${prevMod[0]}/index.html`, "← 上一模块", prevMod[1]]
: [null, "← 上一模块", "已经是第一个模块"];
const idxNext = nextMod
? [`../${nextMod[0]}/index.html`, "下一模块 →", nextMod[1]]
: [`../../index.html#${nextStage}`, "下一模块 →", `阶段 ${nextStage.slice(1)} · ${STAGE_TITLE[nextStage]}`];
const idxBody = head(`${m.title} · 阶段 ${m.stage.num} 模块 ${m.no} · SRE 从零到成熟`,
`${m.title} 模块目录:共 ${m.chapters.length} 章、${secTotal} 个小节。`) +
` <div class="modhero">
<span class="mh-no">阶段 ${m.stage.num} · 模块 ${m.no} / ${m.total}</span>
<h1>${esc(m.title)}</h1>
<p class="mh-sub">${esc(m.sub)}</p>
<div class="mh-meta">
<span>共 <b>${m.chapters.length}</b> 章</span>
<span><b>${secTotal}</b> 个小节</span>
<span>约 <b>${kilo}</b> 千字</span>
</div>
</div>
<p class="lead">
${reindent(m.lead, " ")}
</p>
<h2 id="chapters-list">章节目录</h2>
<ol class="chaplist">
${chaplist}
</ol>
<div class="box tip">
<span class="bt">怎么用这一模块</span>
<p>左侧是<b>章节目录树</b>:先看章标题快速定位,进入某一章后该章的小节会展开并跟随滚动高亮;点其它章标题可直接跳到对应页面。</p>
<p>每章结尾都有「上一章 / 下一章」可以连续阅读,代码块右上角可以一键复制。</p>
</div>
` +
`
</article>
<nav class="pager">
${pager(...idxPrev, ...idxNext)}
</nav>
<p class="foot">
${esc(m.title)} · 模块目录<br>
<a href="../../index.html">返回学习路径</a>
</p>
</main>
</div>
<button id="toTop" title="回到顶部">↑</button>
<script src="../../assets/doc.js"></script>
</body>
</html>
`;
fs.writeFileSync(path.join(outDir, "index.html"), idxBody, "utf8");
/* ---- 章节页 ---- */
m.chapters.forEach((c, i) => {
const no = i + 1;
const nc = m.chapters[i + 1];
const pc = m.chapters[i - 1];
mod.crumbTail = `<a href="index.html">${esc(m.title)}</a><span class="sep">/</span><b>第 ${no} 章</b>`;
mod.footTail = `第 ${no} 章 ${c.title}`;
const pv = pc
? [`${pc.file}.html`, "← 上一章", `第 ${no - 1} 章 · ${pc.title}`]
: ["index.html", "← 模块目录", m.title];
const nx = nc
? [`${nc.file}.html`, "下一章 →", `第 ${no + 1} 章 · ${nc.title}`]
: ["index.html", "回到 →", `${m.title} 章节目录`];
const html = head(`${c.title} · ${m.title} · SRE 从零到成熟`,
`${m.title} 第 ${no} 章:${c.title}。本章 ${(c.html.match(/<h3 id="/g) || []).length} 个小节。`) +
` <p class="chapnav">
<a href="index.html">${esc(m.title)}</a>
<span>·</span>
<span>第 <b class="pos">${no}</b> / ${m.chapters.length} 章</span>
</p>
<h2 id="${c.id}"><span class="n">${no}</span>${esc(c.title)}</h2>
${reindent(c.html, " ")}
` +
`
</article>
<nav class="pager">
${pager(...pv, ...nx)}
</nav>
<p class="foot">
${esc(m.title)} · 第 ${no} 章 ${esc(c.title)}<br>
<a href="index.html">模块目录</a> · <a href="../../index.html">返回学习路径</a>
</p>
</main>
</div>
<button id="toTop" title="回到顶部">↑</button>
<script src="../../assets/doc.js"></script>
</body>
</html>
`;
fs.writeFileSync(path.join(outDir, c.file + ".html"), html, "utf8");
});
return { dir: m.dir, chapters: m.chapters.length, secs: secTotal, chars: m._total };
}
/* ---------------------------------------------------------------- 入口 */
const argv = process.argv.slice(2);
const only = argv.includes("--only") ? argv[argv.indexOf("--only") + 1] : null;
const checkOnly = argv.includes("--check") ? argv[argv.indexOf("--check") + 1] : null;
const targets = fs.existsSync(CONTENT)
? fs.readdirSync(CONTENT).filter(f => f.endsWith(".js")).map(f => f.replace(/\.js$/, "")).sort()
: [];
if (!targets.length) { console.error("content/ 下没有内容文件"); process.exit(1); }
const results = [];
for (const name of targets) {
if (only && name !== only) continue;
if (checkOnly && name !== checkOnly) continue;
let m;
try { m = require(path.join(CONTENT, name + ".js")); }
catch (e) { console.error(`✗ ${name}.js 加载失败:${e.message}`); process.exitCode = 1; continue; }
const before = problems.length;
const ok = validate(m, name);
if (!ok) {
console.error(`✗ ${name}(${problems.length - before} 个问题)`);
problems.slice(before).forEach(x => console.error(" - " + x));
process.exitCode = 1;
continue;
}
if (checkOnly) { results.push({ dir: m.dir, chapters: m.chapters.length, chars: m._total, dry: true }); continue; }
results.push(generate(m));
console.log(`✓ modules/${m.dir}:${m.chapters.length} 章 / ${m._total} 字`);
}
if (results.length && !checkOnly) {
console.log("\n小计:" + results.map(r => `${r.dir}=${r.chars}`).join(" "));
console.log("合计 " + results.reduce((n, r) => n + r.chars, 0) + " 字");
}
if (problems.length) { console.error(`\n共 ${problems.length} 个问题`); process.exit(1); }
if (checkOnly && results.length) console.log("OK 校验通过:" + results.map(r => r.dir).join(", "));