feat: 阶段 6(成熟·从执行者到影响力)详解上线,全站 29 个模块收官
新增 4 个模块、52 章 / 164 小节、约 21.3 万字,全站 343 → 399 页。
目录页 7 个阶段全部显示「详解已上线」,不再有「详解筹备中」。
阶段 6 · 成熟(s6-01 … s6-04)
- 架构评审与可运维性设计:36 项上线前评审清单与评审纪要模板(三选一结论栏)、
容量依赖 / 降级限流位 / 可观测 / 数据一致性 / 成本 / 回滚七类评审、可运维性五要素、
技术-业务-老板翻译对照表、四类灾难推演(单点 / 级联 / 数据损坏 / 误操作)
- 数据驱动的可靠性治理:五指标度量体系与互相约束、SLO 达成率分母陷阱、
MTTR 四段拆解与三种注水、变更失败率口径冻结、Toil 占比口径、告警噪声比、
可靠性健康度季度报表模板、资源/容量/人力排序算例、分层汇报、季度复盘立项单
- 影响力与带人:ADR 模板与 CI 完整性检查、四份规范的可检查条款(告警/日志/发布/值班)、
标准落地三段推广与四类阻力、四层门禁与门禁自身指标、带新人 P0–P3 与 Code Review 清单、
跨团队共同目标、冲突与甩锅化解、无授权影响力五杠杆、标准采纳率口径卡
- 职业路径与个人品牌:四条路线能力重心对比、六维 L1–L4 自评表、
四类面试题各 3 道真题 + 框架 + 失分点、作品集素材判据、12 字段故障案例库模板、
个人品牌、持续学习技术雷达与 AI 协作边界
脚手架 .sre-s23
- gen.js:CHAIN 扩到 29 个模块;新增链尾判定——最后一个模块的 pager 指向
../../index.html(「全部读完 →」),不再生成 #s7 死锚点
- SPEC.md:第 6 节换为阶段 6 的 4 个模块知识点,阶段 4/5 降为附录 A
- coverage.js:关键词表扩到 22 个模块
- 新增 scan-escapes.js / scan-detail.js / fix-esc2.js(见下)
- README.md:补充链尾 pager 说明与全站进度表
修复:模板字面量的第三类静默损坏(51 处,涉 8 个模块)
上一批只覆盖了 `\"` 与行尾 `\`。这次发现 `\X` 被 JS 解释掉的整类问题:
- jq 插值 `\(.metric.le)` 退化成 `(.metric.le)`,输出变成字面文本(s3-01-slo 9 处)
- grep 正则 `\.` `\|` `\[` `\]` 丢反斜杠,语义被放宽或交替失效
(s4-03-iac 11 处、s4-02-gitops 9 处、s5-03-perf 1 处、s6-01-review 1 处)
- printf / curl 格式串里的 `\n` 变成真实换行,命令被拆成两行,在 awk 里直接语法错误
(s6-01-review 12 处、s3-04-chaos 4 处、s3-01-slo 2 处、s2-02-logs 2 处、s2-03-trace 1 处)
- kubectl jsonpath 里的 `argocd\.argoproj\.io` 点号失义(计入上面的 s4-02-gitops)
刻意保留两类:`\x24{{ }}` 是渲染 `${ }` 的既有技巧;展示型输出块里的 `\t` 渲染成
真实制表符(对齐更好,且 `\t` 退化后在 awk / printf / cut 中行为完全一致,无害)。
新增 fix-esc2.js 负责修复,scan-escapes.js / scan-detail.js 负责扫描与人工判定。
校验结果
- check-pages:OK 全部校验通过(共 399 个页面)
- check-pre:OK 所有 JSON 代码块均可解析
- verify-template:OK 新页面只使用既有样式
- coverage:OK 全部知识点关键词均已覆盖(22 个模块)
- check-pages-table:29 条路由,0 条死链,7 个阶段全部「已上线」
- fix-esc:22 个模块残留 `\"` 与行尾 `\` 均为 0
- scan-escapes:仅剩 49 处刻意保留项(43 处 `\t`、6 处 `\x24`)
- pager 链路:s5-05-toil → s6-01 → … → s6-04-career → ../../index.html
- 无头浏览器核对:7 个阶段上线数全部满额,「详解筹备中」不再渲染出任何条目
其他
- 站点 README:目录树补 4 个模块、内容表新增 4 行,注明 29 个模块全部上线
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
# 阶段 2–5 内容生产脚手架
|
||||
# 阶段 2–6 内容生产脚手架
|
||||
|
||||
这个目录是**构建工具**,不是站点的一部分。站点(`knowledge/sre-learning-path/`)仍然是纯静态 HTML,
|
||||
不依赖这里的任何文件即可打开。留着它是为了让后续阶段(6)的模块能用同一套模板快速产出。
|
||||
不依赖这里的任何文件即可打开。29 个模块的详解已全部产出,这里保留下来是为了以后**改内容或加模块**
|
||||
时能重放同一套流程。
|
||||
|
||||
## 内容清单
|
||||
|
||||
@@ -9,7 +10,7 @@
|
||||
|---|---|
|
||||
| `SPEC.md` | 内容编写规范:数据文件格式、可用 HTML 片段、写作要求、自查清单、10 个模块的知识点附录 |
|
||||
| `gen.js` | 生成器:读 `content/*.js`,产出 `modules/<dir>/index.html` 与 `NN-*.html` |
|
||||
| `content/*.js` | 18 个模块的内容源(阶段 2/3 的 8 个 + 阶段 4/5 的 10 个) |
|
||||
| `content/*.js` | 22 个模块的内容源(阶段 2/3 的 8 个 + 阶段 4/5 的 10 个 + 阶段 6 的 4 个) |
|
||||
| `fix-esc.js` | 查/修 JS 模板字面量导致的两类静默损坏(见下) |
|
||||
| `check-pre.js` | 体检生成后的代码块:`data-lang="json"` 的块能否 `JSON.parse` |
|
||||
| `verify-template.js` | 样式一致性:新页面是否只用阶段 0/1 已有的 class |
|
||||
@@ -77,28 +78,34 @@ done
|
||||
|
||||
新增章节或调整顺序后,只要重跑第 4–5 步。
|
||||
|
||||
场景 6(下一批)落地时的完整顺序:
|
||||
|
||||
```bash
|
||||
# 1. gen.js 的 CHAIN 补上阶段 6 的 4 个模块(同时补 STAGE_TITLE.s7,如果还有阶段 7)
|
||||
# 2. 按 SPEC.md 写 content/s6-0*.js,逐个:
|
||||
node .sre-s23/gen.js --check s6-01-xxx
|
||||
node .sre-s23/fix-esc.js s6-01-xxx --write
|
||||
node .sre-s23/gen.js --only s6-01-xxx
|
||||
# 3. 全部写完后统一:
|
||||
cd knowledge/sre-learning-path && node tools/build-nav.js && node tools/check-pages.js
|
||||
node D:/code/materials/.sre-s23/check-pre.js s6-01-xxx ...
|
||||
node D:/code/materials/.sre-s23/verify-template.js s6-01-xxx ...
|
||||
node D:/code/materials/.sre-s23/coverage.js
|
||||
node D:/code/materials/.sre-s23/check-pages-table.js
|
||||
```
|
||||
|
||||
最后把站点 `index.html` 的 `PAGES` 补上 `s6-0`…`s6-3`,并更新站点 `README.md` 的目录树与内容表
|
||||
(表格数字用 `node .sre-s23/metrics.js` 生成)。
|
||||
|
||||
`CHAIN` 里每加一个模块,**它前一个模块的目录页 pager 也会变**(指向新的「下一模块」),
|
||||
所以新增模块后要连同前一个模块一起重新生成,例如:
|
||||
所以新增模块后要连同前一个模块一起重新生成(`--only` 不支持多值,分两次跑):
|
||||
|
||||
```bash
|
||||
node .sre-s23/gen.js --only s4-01-k8s --only s3-04-chaos # 不支持多值,实际分两次跑
|
||||
node .sre-s23/gen.js --only s6-01-review
|
||||
node .sre-s23/gen.js --only s5-05-toil
|
||||
```
|
||||
|
||||
## 链尾模块的 pager
|
||||
|
||||
`CHAIN` 的最后一个模块没有「下一模块」。`gen.js` 会看 `STAGE_TITLE` 里有没有下一个阶段:
|
||||
|
||||
- 有(例如 `s5-05-toil` → `s6`)→ pager 指向 `../../index.html#s6`,文案「阶段 6 · 成熟」
|
||||
- 没有(`s6-04-career` 是全站最后一个模块)→ pager 指向 `../../index.html`,文案「全部读完 →」
|
||||
|
||||
所以**不要给最后一个阶段补一个不存在的 `STAGE_TITLE.s7`**,否则会生成 `#s7` 死链。
|
||||
`check-pages.js` 会校验锚点,但只在目录页真的没有 `id="s7"` 时报错——加之前先想清楚。
|
||||
|
||||
## 全站进度
|
||||
|
||||
| 阶段 | 模块 | 状态 |
|
||||
|---|---|---|
|
||||
| 0 打地基 | 3 | 已上线 |
|
||||
| 1 服务上线 | 4 | 已上线 |
|
||||
| 2 看得见 | 4 | 已上线 |
|
||||
| 3 稳得住 | 4 | 已上线 |
|
||||
| 4 上规模 | 5 | 已上线 |
|
||||
| 5 扛得住 | 5 | 已上线 |
|
||||
| 6 成熟 | 4 | 已上线 |
|
||||
|
||||
合计 29 个模块;`content/` 里有 22 个内容源(阶段 0/1 的模块是早期手写的,没有走生成器)。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# 阶段 4 / 5 内容编写规范(SPEC)
|
||||
# 阶段 6 内容编写规范(SPEC)
|
||||
|
||||
你只负责**写内容数据文件**,不要碰站点的 HTML、`index.html`、`assets/`、`tools/`。
|
||||
页面 HTML(页头、面包屑、侧栏容器、章节定位条、上一/下一章)由生成器统一产出,
|
||||
@@ -12,12 +12,12 @@
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
dir: "s4-01-k8s", // 必须与文件名一致,格式 sN-NN-slug
|
||||
title: "Kubernetes 核心", // 模块标题
|
||||
sub: "阶段 4 · 云原生与平台工程 · 控制循环、工作负载、网络存储与排障", // 模块目录页副标题
|
||||
stage: { num: 4, title: "上规模" }, // 所属阶段
|
||||
dir: "s6-01-review", // 必须与文件名一致,格式 sN-NN-slug
|
||||
title: "架构评审与可运维性设计", // 模块标题
|
||||
sub: "阶段 6 · 成熟 · 上线前评审清单、可运维性设计与灾难推演", // 模块目录页副标题
|
||||
stage: { num: 6, title: "成熟" }, // 所属阶段
|
||||
no: 1, // 本模块在阶段内的序号
|
||||
total: 5, // 本阶段模块总数
|
||||
total: 4, // 本阶段模块总数
|
||||
|
||||
// 模块目录页的导语,HTML 片段。必须包含「模块定位 / 学完之后你应该能 / 前置 / 建议投入」四段
|
||||
lead: `
|
||||
@@ -195,8 +195,14 @@ node D:\code\materials\.sre-s23\gen.js --check <dir>
|
||||
| `s5-03-perf` | 性能分析与内核调优 |
|
||||
| `s5-04-security` | 安全与合规运维 |
|
||||
| `s5-05-toil` | 效率与 Toil 消除 |
|
||||
| `s6-01-review` | 架构评审与可运维性设计 |
|
||||
| `s6-02-governance` | 数据驱动的可靠性治理 |
|
||||
| `s6-03-influence` | 影响力与带人 |
|
||||
| `s6-04-career` | 职业路径与个人品牌 |
|
||||
|
||||
**不要**链接阶段 6 的目录页(尚不存在,会变死链)。
|
||||
阶段 6 是**最后一个阶段**,没有阶段 7 的目录页。最后一章写「下一步」时只写文字指引
|
||||
(例如指路到持续学习或作品集沉淀),**不要写任何指向下一阶段的链接**。
|
||||
`gen.js` 对链尾模块的 pager 会自动指向 `../../index.html`(「返回学习路径目录」)。
|
||||
|
||||
---
|
||||
|
||||
@@ -225,11 +231,66 @@ node D:\code\materials\.sre-s23\gen.js --check <dir>
|
||||
|
||||
---
|
||||
|
||||
## 6. 附录:本次 10 个模块必须覆盖的知识点
|
||||
## 6. 附录:本次 4 个模块必须覆盖的知识点
|
||||
|
||||
下面每一条都来自学习路径目录页,**必须逐条落到某一章的正文里**,不能只在标题里提一句。
|
||||
建议章节数 13(第 12 章速查表、第 13 章自测),可按内容深浅增减,但不少于 11 章。
|
||||
|
||||
阶段 6 的三个特性,写作时必须体现:
|
||||
|
||||
- **这是「从做事到影响组织」的阶段**,内容高度依赖真实案例与可复用模板,不能写成人力资源话术。
|
||||
- **每一章都要给可核对的判据**:评审清单要能逐条打勾、报表要给出指标口径与取数语句、
|
||||
规范要给出可检查的条款、路线选择要给出对比维度表。凡是「加强沟通」「提升意识」这类
|
||||
无法验证的表述,一律删掉。
|
||||
- **允许并鼓励引用前面阶段的具体内容**(例如评审清单里引 `s3-02-ha` 的冗余判据、
|
||||
报表里引 `s3-01-slo` 的错误预算、规范里引 `s2-01-metrics` 的标签基数),
|
||||
这一阶段的价值就在于把前面学到的东西**组合成组织级机制**。
|
||||
|
||||
### `s6-01-review` · 架构评审与可运维性设计(no=1,total=4,tag=adv)
|
||||
- 上线前评审清单:容量、依赖、降级、可观测、数据一致性、成本、回滚方案
|
||||
- 可运维性设计:无状态、幂等、限流位、配置热更、灰度开关要设计进去
|
||||
- 权衡表达:把「稳定性 vs 交付速度」翻译成业务和老板能听懂的话
|
||||
- 灾难推演:单点、级联、数据损坏、误操作四类场景逐步推演
|
||||
- 交付物:主导一次新系统上线评审,输出带明确结论的评审纪要与风险清单
|
||||
- 验收:评审后上线,故障率与回滚率有可观测的下降
|
||||
|
||||
### `s6-02-governance` · 数据驱动的可靠性治理(no=2,total=4,tag=adv)
|
||||
- 建立度量体系:SLO 达成率、MTTR、变更失败率、Toil 占比、告警噪声比
|
||||
- 用数据做决策:资源投入、容量预算、人力分配的排序依据
|
||||
- 分层汇报:给技术团队和管理层各准备一版,结论一致、语言不同
|
||||
- 改进机制:季度可靠性复盘,把趋势问题变成长期项目
|
||||
- 交付物:建立一张「可靠性健康度」季度报表,并在团队复盘会上讲解与答疑
|
||||
- 验收:关键决策都有数据支撑,能说清投入与产出
|
||||
|
||||
### `s6-03-influence` · 影响力与带人(no=3,total=4,tag=cont)
|
||||
- 技术决策:写 ADR,记录背景、备选项、结论与后果,避免反复争论
|
||||
- 传承:内部分享、带新人、Runbook 与 Code Review 的评审机制
|
||||
- 推动标准:告警规范、日志规范、发布规范、值班规范
|
||||
- 跨团队协作:与研发、产品、安全、DBA 建立共同目标而不是互相甩锅
|
||||
- 交付物:在团队内推动一项标准化(例如告警规范),落地并度量效果
|
||||
- 验收:你不在场时,团队仍按你推动的标准做事
|
||||
|
||||
### `s6-04-career` · 职业路径与个人品牌(no=4,total=4,tag=cont)
|
||||
- 路线选择:SRE / 平台工程 / 云原生架构 / 稳定性负责人,各有不同的能力重心
|
||||
- 面试准备:故障排查题、系统设计题、SLO 设计题、脚本题四类专项训练
|
||||
- 作品集:开源项目、技术博客、内部分享材料、可展示的自动化成果
|
||||
- 持续学习:跟住 K8s 生态、eBPF 可观测、平台工程与 AIOps 的演进
|
||||
- 交付物:整理一份个人作品集与「我解决过的 5 个典型故障」案例库
|
||||
- 验收:能在 30 分钟内讲清自己的技术深度与为业务创造的价值
|
||||
|
||||
### 阶段内的相互引用
|
||||
|
||||
- `s6-01-review` 是阶段 6 的入口,要大量引阶段 3:`s3-02-ha`(冗余与单点)、
|
||||
`s3-03-capacity`(容量模型)、`s3-01-slo`(SLO 与错误预算)、`s3-04-chaos`(演练验证)。
|
||||
- `s6-02-governance` 要引阶段 2/3/5:`s2-01-metrics`(指标口径)、`s2-04-dashboard`(看板分层)、
|
||||
`s3-01-slo`(SLO 达成率)、`s5-01-oncall`(MTTR 口径)、`s5-05-toil`(Toil 占比)。
|
||||
- `s6-03-influence` 要引 `s5-02-postmortem`(复盘文化 → 无指责)、`s2-01-metrics`(告警规范)。
|
||||
- `s6-04-career` 要引 `s5-02-postmortem`(故障案例库)、`s4-05-platform`(作品集素材)。
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:阶段 4 / 5 的知识点(已上线,保留备查)
|
||||
|
||||
### 阶段 4 · 上规模
|
||||
|
||||
#### `s4-01-k8s` · Kubernetes 核心(no=1,total=5)
|
||||
@@ -304,7 +365,7 @@ node D:\code\materials\.sre-s23\gen.js --check <dir>
|
||||
- 知识沉淀:Runbook、决策记录(ADR)、FAQ、值班手册
|
||||
- 与研发协作:可运维性评审、SLO 谈判、上线门禁,把要求前置到设计阶段
|
||||
|
||||
### 阶段内的相互引用
|
||||
### 阶段 4 / 5 的跨阶段引用
|
||||
|
||||
- 阶段 4 的模块大量依赖阶段 1:容器与镜像 `s1-03-container`、CI/CD `s1-04-cicd`。
|
||||
平台工程要引阶段 2/3:`s2-01-metrics`、`s3-01-slo`。
|
||||
|
||||
@@ -770,7 +770,7 @@ $ docker run --rm -v /tmp/fbtest:/logs -v /tmp/fbtest/parsers.conf:/fluent-bit/e
|
||||
cr.fluentbit.io/fluent/fluent-bit:3.1 -c /fluent-bit/etc/fluent-bit.conf
|
||||
|
||||
# ④ 预期输出:2 条记录,不是 7 条
|
||||
# {"log":"2024-06-12T20:14:03.481Z ERROR ...\nat com.acme.OrderDao...\nCaused by: ..."}
|
||||
# {"log":"2024-06-12T20:14:03.481Z ERROR ...\\nat com.acme.OrderDao...\\nCaused by: ..."}
|
||||
# {"log":"2024-06-12T20:14:04.002Z INFO 订单创建成功 trace_id=9ac31b02"}
|
||||
# 如果看到 7 条,说明 multiline.parser 没生效或 rules 没匹配上</pre>
|
||||
<p>更进一步:把 <code>[OUTPUT]</code> 换成 <code>Name loki / Host localhost / Port 3100</code>,
|
||||
|
||||
@@ -1873,7 +1873,7 @@ datasources:
|
||||
|
||||
<h3 id="sec-11-4">11.4 验证步骤:从一次慢请求到具体 SQL</h3>
|
||||
<ol class="steps">
|
||||
<li><b>启动并等健康。</b><code>docker compose up -d --build</code>,然后 <code>docker compose ps</code> 确认全部 Up;<code>curl -s localhost:4318 -o /dev/null -w '%{http_code}\n'</code> 返回 405 说明 OTLP HTTP 端口在听。</li>
|
||||
<li><b>启动并等健康。</b><code>docker compose up -d --build</code>,然后 <code>docker compose ps</code> 确认全部 Up;<code>curl -s localhost:4318 -o /dev/null -w '%{http_code}\\n'</code> 返回 405 说明 OTLP HTTP 端口在听。</li>
|
||||
<li><b>先打正常请求,确认链路是通的。</b>见下方命令与预期。</li>
|
||||
<li><b>打慢请求,用 TraceQL 找到它。</b></li>
|
||||
<li><b>算出每一段的占比</b>,得出「下一步该优化谁」。</li>
|
||||
|
||||
@@ -450,7 +450,7 @@ curl -s --data-urlencode "query=$q" http://localhost:9090/api/v1/query | jq -r '
|
||||
输出大于 1 或为 <code>NaN</code>,说明分子包含分母没有的序列(典型原因:<code>sum by</code> 维度不一致、分母被 label 过滤)。</li>
|
||||
<li><b>验证分子不大于分母</b>:把两条查询分开跑,肉眼对比每秒请求数。分子应严格小于等于分母。</li>
|
||||
<li><b>验证延迟阈值桶存在</b>:
|
||||
<pre data-lang="bash" data-name="确认 le=1 的桶被真正上报">curl -s --data-urlencode 'query=count(http_request_duration_seconds_bucket{job="order-api"}) by (le)' http://localhost:9090/api/v1/query | jq -r '.data.result[] | "\(.metric.le) \(.value[1])"'</pre>
|
||||
<pre data-lang="bash" data-name="确认 le=1 的桶被真正上报">curl -s --data-urlencode 'query=count(http_request_duration_seconds_bucket{job="order-api"}) by (le)' http://localhost:9090/api/v1/query | jq -r '.data.result[] | "\\(.metric.le) \\(.value[1])"'</pre>
|
||||
预期看到 <code>le</code> 的完整列表(<code>0.05 0.1 0.25 0.5 1 2.5 5 +Inf</code>)。<b>看不到 <code>1</code> 就说明客户端 SDK 的桶配置里没有 1 秒边界</b>,你的延迟 SLI 会用到插值或直接失效——这是现场最常见的坑,必须改 SDK 的 bucket 配置并重新发版。</li>
|
||||
<li><b>把验证固化成 recording rule</b>:让 <code>record: slo:sli_ratio:5m</code> 产出结果,这样 Grafana、告警、门禁读的是同一个数字,不会出现「看板和告警算法不同」的两张皮。</li>
|
||||
</ol>
|
||||
@@ -877,7 +877,7 @@ curl -s --data-urlencode "query=sum(rate(http_requests_total{job=\\"order-api\\"
|
||||
同时用 <code>promtool test rules</code> 写单元测试:喂入一段人为构造的时序(错误率从 0 升到 12%),断言 <code>SLOHighBurnRate_Fast1h</code> 在 5 分钟后进入 firing。这是唯一能在不制造真实故障的前提下验证阈值配对是否正确的方法。</li>
|
||||
<li><b>制造可控故障</b>:在 staging 用 <code>vegeta</code> 把 10% 的请求打到 <code>/api/v1/orders?force_error=1</code>(一个只在非生产开启的开关),持续 10 分钟:
|
||||
<pre data-lang="bash" data-name="制造 10% 错误率持续 10 分钟">echo "GET http://staging-order.internal/api/v1/orders?force_error=1" > target.txt
|
||||
printf "rate: 200\nfor: 10m\n" > attack.conf
|
||||
printf "rate: 200\\nfor: 10m\\n" > attack.conf
|
||||
vegeta attack -targets=target.txt -rate=200 -duration=10m -header="X-Slo-Burn: 10pct" | vegeta report</pre>
|
||||
</li>
|
||||
<li><b>盯住三条曲线</b>:<code>slo:burn_rate:5m</code>、<code>slo:burn_rate:1h</code>、<code>slo:error_budget_remaining:28d</code>。预期 5m 在 1 分钟内冲过 100,1h 在约 4–5 分钟后越过 14.4,告警在 <code>for: 2m</code> 后进入 firing。</li>
|
||||
@@ -1287,7 +1287,7 @@ GATE=BLOCK reason=error_budget_exhausted remaining=6.8%
|
||||
<span class="bt">动手 · 把门禁跑通并验证三种分支</span>
|
||||
<p>前置:<code>curl</code>、<code>jq</code>、一个非生产环境的 Prometheus(<code>PROM_URL</code> 指过去)。</p>
|
||||
<ol class="steps">
|
||||
<li><b>确认指标存在</b>:<code>curl -sS --get "$PROM_URL/api/v1/query" --data-urlencode 'query=slo:error_budget_remaining:28d' | jq -r '.data.result[] | "\(.metric.slo) \(.value[1])"'</code>。没有输出就先补第 6 章的 recording rules。</li>
|
||||
<li><b>确认指标存在</b>:<code>curl -sS --get "$PROM_URL/api/v1/query" --data-urlencode 'query=slo:error_budget_remaining:28d' | jq -r '.data.result[] | "\\(.metric.slo) \\(.value[1])"'</code>。没有输出就先补第 6 章的 recording rules。</li>
|
||||
<li><b>测「允许全量」分支</b>:用 <code>--data-urlencode 'query=...'</code> 造一个假指标不方便,简单做法是先把脚本里的阈值临时改成极低(比如 <code>r >= 0.0001</code>)跑一次,确认退出码 0 与输出内容。</li>
|
||||
<li><b>测「阻断」分支</b>:把阈值改成 <code>r >= 0.9999</code>,再跑一次,预期退出码 20,并打印政策条款与允许项。</li>
|
||||
<li><b>测「例外」分支</b>:<code>./scripts/slo-gate.sh order-api-availability-99.9 order-api reliability-exception; echo "exit=$?"</code>,预期退出码 <b>10</b>(仍是金丝雀,不是全量)——<b>例外只放宽冻结,不放宽风险</b>。</li>
|
||||
@@ -1642,12 +1642,12 @@ curl -X POST http://localhost:9090/-/reload
|
||||
# 4. 确认 recording rules 已产出序列
|
||||
curl -sS --get http://localhost:9090/api/v1/query \\
|
||||
--data-urlencode 'query=count by (__name__)({__name__=~"slo:.*"})' \\
|
||||
| jq -r '.data.result[] | "\(.metric.__name__) \(.value[1])"'
|
||||
| jq -r '.data.result[] | "\\(.metric.__name__) \\(.value[1])"'
|
||||
# 预期:列出 slo:burn_rate:5m、slo:burn_rate:1h、slo:error_budget_remaining:28d 等
|
||||
|
||||
# 5. 确认告警规则状态为 inactive(而不是 pending/firing 或缺失)
|
||||
curl -sS http://localhost:9090/api/v1/rules \\
|
||||
| jq -r '.data.groups[].rules[] | select(.type=="alerting") | "\(.name) \(.state)"'</pre>
|
||||
| jq -r '.data.groups[].rules[] | select(.type=="alerting") | "\\(.name) \\(.state)"'</pre>
|
||||
<p>第 2 步的单元测试文件(<code>promtool test rules</code>)值得认真写一份,因为它能在不制造任何真实故障的前提下验证「阈值配对是否正确」。最小可用的测试:</p>
|
||||
<pre data-lang="yaml" data-name="tests/slo-order-api.test.yml(最小可用)">rule_files:
|
||||
- ../rules/slo-order-api.yml
|
||||
@@ -1730,7 +1730,7 @@ while true; do
|
||||
| jq -r '.data.result[0].value[1] // "NA"'
|
||||
done
|
||||
curl -sS http://localhost:9090/api/v1/rules \\
|
||||
| jq -r '.data.groups[].rules[] | select(.state=="firing") | "FIRING: \(.name)"'
|
||||
| jq -r '.data.groups[].rules[] | select(.state=="firing") | "FIRING: \\(.name)"'
|
||||
sleep 30
|
||||
done</pre>
|
||||
<p><b>预期时间线</b>(我们实测值):</p>
|
||||
|
||||
@@ -1860,10 +1860,10 @@ b_succ=$(get success_p99min "$BEFORE"); a_succ=$(get success_p99min "$AFTER")
|
||||
b_p99=$(get p99_ms "$BEFORE"); a_p99=$(get p99_ms "$AFTER")
|
||||
b_pool=$(get pool_peak "$BEFORE"); a_pool=$(get pool_peak "$AFTER")
|
||||
|
||||
printf '%-14s %10s %10s %10s\n' 指标 修复前 修复后 判据
|
||||
printf '%-14s %10s %10s %10s\n' 成功率 "$b_succ" "$a_succ" ">= $SUCC_MIN"
|
||||
printf '%-14s %10s %10s %10s\n' P99毫秒 "$b_p99" "\${a_p99}" "<= $P99_MAX_MS"
|
||||
printf '%-14s %10s %10s %10s\n' 连接池峰值 "$b_pool" "$a_pool" "<= 180"
|
||||
printf '%-14s %10s %10s %10s\\n' 指标 修复前 修复后 判据
|
||||
printf '%-14s %10s %10s %10s\\n' 成功率 "$b_succ" "$a_succ" ">= $SUCC_MIN"
|
||||
printf '%-14s %10s %10s %10s\\n' P99毫秒 "$b_p99" "\${a_p99}" "<= $P99_MAX_MS"
|
||||
printf '%-14s %10s %10s %10s\\n' 连接池峰值 "$b_pool" "$a_pool" "<= 180"
|
||||
|
||||
fail=0
|
||||
awk -v v="$a_succ" -v m="$SUCC_MIN" 'BEGIN{exit !(v+0 >= m+0)}' || { echo "✗ 成功率未达标"; fail=1; }
|
||||
|
||||
@@ -811,8 +811,8 @@ argocd app manifests order-api-prod | grep -E "^(kind| name):" | paste - - | so
|
||||
comm -23 /tmp/live.txt /tmp/git.txt | head -20
|
||||
|
||||
# 3) 判断谁是追踪者:看 tracking label / annotation
|
||||
kubectl -n order-prod get cm suspicious-cm -o jsonpath="{.metadata.labels.argocd\.argoproj\.io/instance}"; echo
|
||||
kubectl -n order-prod get cm suspicious-cm -o jsonpath="{.metadata.annotations.argocd\.argoproj\.io/tracking-id}"; echo</pre>
|
||||
kubectl -n order-prod get cm suspicious-cm -o jsonpath="{.metadata.labels.argocd\\.argoproj\\.io/instance}"; echo
|
||||
kubectl -n order-prod get cm suspicious-cm -o jsonpath="{.metadata.annotations.argocd\\.argoproj\\.io/tracking-id}"; echo</pre>
|
||||
<p>Argo CD 的追踪标识有两种:<code>app.kubernetes.io/instance</code> 标签(旧)与 <code>argocd.argoproj.io/tracking-id</code> 注解(新,格式为 <code><app>:<group>/<kind>:<namespace>/<name></code>)。<code>argocd-cm</code> 的 <code>application.resourceTrackingMethod</code> 可设为 <code>label</code> / <code>annotation</code> / <code>annotation+label</code>。<b>切换追踪方式时,所有应用需要一次全量同步来补写标识,期间孤儿检测会大面积误报</b>,要在低峰做。</p>
|
||||
|
||||
<div class="box case">
|
||||
@@ -845,7 +845,7 @@ kubectl -n drift-demo autoscale deployment web --min=2 --max=10 --cpu-percent=65
|
||||
kubectl -n drift-demo get hpa</pre>
|
||||
预期 <code>TARGETS</code> 一列显示 <code><unknown>/65%</code>(没有 metrics-server 时正常)。</li>
|
||||
<li><b>把这份状态纳入 Git 并交给 Argo CD</b>:
|
||||
<pre data-lang="bash" data-name="用 Application 管理它">mkdir -p /tmp/drift && kubectl -n drift-demo get deploy web -o yaml | grep -v "resourceVersion\|uid\|creationTimestamp\|status" > /tmp/drift/deploy.yaml
|
||||
<pre data-lang="bash" data-name="用 Application 管理它">mkdir -p /tmp/drift && kubectl -n drift-demo get deploy web -o yaml | grep -v "resourceVersion\\|uid\\|creationTimestamp\\|status" > /tmp/drift/deploy.yaml
|
||||
cd /tmp/drift && git init -q && git add . && git -c user.email=a@b -c user.name=a commit -qm init
|
||||
printf "%s\\n" "apiVersion: argoproj.io/v1alpha1" "kind: Application" "metadata:" " name: drift-demo" " namespace: argocd" "spec:" " project: default" " source:" " repoURL: file:///tmp/drift" " targetRevision: HEAD" " path: ." " destination:" " server: https://kubernetes.default.svc" " namespace: drift-demo" " syncPolicy:" " automated:" " prune: true" " selfHeal: true" | kubectl apply -f -
|
||||
sleep 25; argocd app get drift-demo | head -6</pre></li>
|
||||
@@ -1093,10 +1093,10 @@ spec:
|
||||
|
||||
<h3 id="sec-8-4">SOPS 与「必须动态」的东西</h3>
|
||||
<pre data-lang="yaml" data-name=".sops.yaml:按路径选择加密收件人">creation_rules:
|
||||
- path_regex: envs/prod/.*\.yaml$
|
||||
- path_regex: envs/prod/.*\\.yaml$
|
||||
encrypted_regex: "^(data|stringData|password|tokens?)$"
|
||||
age: age1qz7m3k9v2ldhj4x8p0c5y6n1r2t3u4w5e6s7d8f9g0h1j2k3l4m5n
|
||||
- path_regex: envs/staging/.*\.yaml$
|
||||
- path_regex: envs/staging/.*\\.yaml$
|
||||
age: age1stg0000000000000000000000000000000000000000000000000000</pre>
|
||||
<p><code>encrypted_regex</code> 只加密指定字段,其余字段(镜像 tag、副本数)保持可读,<b>这解决了「加密后无法 code review」的问题</b>:评审时能看清这次改了什么,只是看不到密文内容。SOPS 的代价在 GitOps 集成:Argo CD 原生不认 SOPS,需要 <code>ksops</code> 插件(Kustomize 的 generator plugin)或在 CI 里先解密再提交渲染结果——后者又回到「明文进过某个仓库」的问题。</p>
|
||||
<p><b>哪些东西永远不该放 Git,无论加密与否:</b></p>
|
||||
|
||||
@@ -477,7 +477,7 @@ terraform init -no-color | tail -2 && terraform apply -auto-approve -no-
|
||||
</li>
|
||||
<li><b>看清模块实例地址</b>:
|
||||
<pre data-lang="bash" data-name="模块地址里的实例键">terraform state list | sort
|
||||
terraform state list | grep -c 'module.web\["prod"\]'</pre>
|
||||
terraform state list | grep -c 'module.web\\["prod"\\]'</pre>
|
||||
预期:<code>module.web["dev"].local_file.index</code>、<code>module.web["dev"].local_file.manifests[0]</code>、<code>module.web["prod"].local_file.manifests[2]</code>……以及计数 <code>4</code>。<b>这就是 <code>for_each</code> 的价值</b>:把 dev 的 replicas 改成 0 时,只有 <code>module.web["dev"].local_file.manifests[0]</code> 这一条被销毁,prod 的地址完全不动。如果这里用的是 <code>count</code>,删中间一个环境会让后面所有环境的索引整体位移,plan 里会出现大面积的 <code>-/+</code>。
|
||||
</li>
|
||||
<li><b>验证契约校验会拦住错误输入</b>:把 <code>replicas = 3</code> 改成 <code>replicas = "three"</code> 再跑 <code>terraform validate</code>,预期报错 <code>Inappropriate value for attribute "replicas": a number is required.</code>。这一步证明了第 3.2 节的 <code>type</code> 约束确实在 CI 阶段生效,而不是等到 apply 才炸。</li>
|
||||
@@ -1976,8 +1976,8 @@ echo "--- 名字含 lab 的安全组"; aws ec2 describe-security-groups --region
|
||||
<tr><td>纳管已有资源</td><td><code>import { to = ..., id = "..." }</code> + <code>plan -generate-config-out=gen.tf</code></td><td>生成代码需人工整理(变量化、补标签、加 lifecycle)后才能合并</td></tr>
|
||||
<tr><td>备份 state</td><td><code>terraform state pull > backup-$(date +%F-%H%M).json</code></td><td>只在改动窗口内保留;不要提交进 Git</td></tr>
|
||||
<tr><td>解锁</td><td><code>terraform force-unlock <LOCK_ID></code></td><td>先确认持锁进程已死;<b>不确定就不要解锁</b></td></tr>
|
||||
<tr><td>统计计划里的销毁项</td><td><code>terraform show -json tfplan | jq -r '[.resource_changes[].change.actions\|join("/")] \| group_by(.) \| map({动作: .[0], 数量: length})'</code></td><td>出现 <code>delete</code> 或 <code>create/delete</code> 即需两人评审</td></tr>
|
||||
<tr><td>扫描 state 里的明文</td><td><code>terraform state pull \| jq -r '.. \| strings' \| grep -Ei 'password\|secret\|token\|PRIVATE KEY'</code></td><td>命中数超过基线即门禁失败;在受控终端上跑</td></tr>
|
||||
<tr><td>统计计划里的销毁项</td><td><code>terraform show -json tfplan | jq -r '[.resource_changes[].change.actions\\|join("/")] \\| group_by(.) \\| map({动作: .[0], 数量: length})'</code></td><td>出现 <code>delete</code> 或 <code>create/delete</code> 即需两人评审</td></tr>
|
||||
<tr><td>扫描 state 里的明文</td><td><code>terraform state pull \\| jq -r '.. \\| strings' \\| grep -Ei 'password\\|secret\\|token\\|PRIVATE KEY'</code></td><td>命中数超过基线即门禁失败;在受控终端上跑</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -1833,7 +1833,7 @@ UID PID cswch/s nvcswch/s Command
|
||||
138
|
||||
147
|
||||
|
||||
$ jcmd 2841 Thread.print | grep -B1 "waiting to lock" | grep -o "inventory\.[A-Za-z.]*" | sort | uniq -c | sort -rn
|
||||
$ jcmd 2841 Thread.print | grep -B1 "waiting to lock" | grep -o "inventory\\.[A-Za-z.]*" | sort | uniq -c | sort -rn
|
||||
144 inventory.StockCache.refreshAll</pre>
|
||||
<p>推理链:<b>①</b> <code>cswch/s = 92410</code>(自愿切换,即在等)而
|
||||
<code>nvcswch/s = 820</code>(被抢 CPU),比例超过 100:1,几乎可以确定是锁;
|
||||
|
||||
1393
.sre-s23/content/s6-01-review.js
Normal file
1393
.sre-s23/content/s6-01-review.js
Normal file
File diff suppressed because it is too large
Load Diff
1758
.sre-s23/content/s6-02-governance.js
Normal file
1758
.sre-s23/content/s6-02-governance.js
Normal file
File diff suppressed because it is too large
Load Diff
3111
.sre-s23/content/s6-03-influence.js
Normal file
3111
.sre-s23/content/s6-03-influence.js
Normal file
File diff suppressed because it is too large
Load Diff
1393
.sre-s23/content/s6-04-career.js
Normal file
1393
.sre-s23/content/s6-04-career.js
Normal file
File diff suppressed because it is too large
Load Diff
@@ -62,7 +62,21 @@ const SPEC = {
|
||||
"端口", "供应链"],
|
||||
"s5-05-toil": ["Toil", "手动", "重复", "自动化", "长期价值", "线性增长", "占比", "50%", "30%",
|
||||
"频率", "耗时", "出错代价", "Runbook", "ADR", "FAQ", "值班手册", "可运维性评审",
|
||||
"SLO 谈判", "上线门禁"]
|
||||
"SLO 谈判", "上线门禁"],
|
||||
|
||||
/* ---------------- 阶段 6 · 成熟 ---------------- */
|
||||
"s6-01-review": ["评审", "容量", "依赖", "降级", "可观测", "数据一致性", "成本", "回滚",
|
||||
"无状态", "幂等", "限流", "配置热更", "灰度", "权衡", "交付速度", "灾难推演",
|
||||
"单点", "级联", "数据损坏", "误操作", "评审纪要", "风险清单"],
|
||||
"s6-02-governance": ["SLO 达成率", "MTTR", "MTTD", "MTTA", "变更失败率", "Toil 占比",
|
||||
"告警噪声比", "报表", "口径", "分母", "资源、容量与人力", "容量预算", "人力分配",
|
||||
"分层汇报", "管理层", "季度", "长期项目", "投入产出"],
|
||||
"s6-03-influence": ["ADR", "备选项", "后果", "告警规范", "日志规范", "发布规范",
|
||||
"值班规范", "采纳率", "带新人", "Code Review", "内部分享", "跨团队",
|
||||
"共同目标", "甩锅", "无授权", "门禁", "度量"],
|
||||
"s6-04-career": ["SRE", "平台工程", "云原生架构", "稳定性负责人", "能力模型",
|
||||
"差距分析", "故障排查", "系统设计", "SLO 设计", "脚本", "作品集", "开源",
|
||||
"博客", "案例库", "个人品牌", "持续学习", "eBPF", "AIOps"]
|
||||
};
|
||||
|
||||
let totalMissing = 0;
|
||||
|
||||
80
.sre-s23/fix-esc2.js
Normal file
80
.sre-s23/fix-esc2.js
Normal file
@@ -0,0 +1,80 @@
|
||||
/* 修复模板字面量的第三类静默损坏:`\X` 被 JS 解释掉。
|
||||
fix-esc.js 只覆盖 `\"` 与行尾 `\`,本脚本覆盖剩余的转义退化。
|
||||
|
||||
只在 <pre>...</pre> 与 <code>...</code> 区域内动手(这些是要给读者看/粘贴的内容)。
|
||||
故意保留的两类:
|
||||
- `\xHH`(例如 `\x24{{ }}` 是刻意用来渲染 `${ }` 的技巧)
|
||||
- `data-lang="text"` 的展示型代码块里的 `\t`(渲染成真实制表符,对齐更好看)
|
||||
|
||||
用法:
|
||||
node .sre-s23/fix-esc2.js <dir> 只报告
|
||||
node .sre-s23/fix-esc2.js <dir> --write 写回
|
||||
*/
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const DIR = path.resolve(__dirname, "content");
|
||||
|
||||
/* JS 会解释或吞掉反斜杠的字符:这些在 shell / regex / awk / jq 里几乎都要保留字面反斜杠 */
|
||||
const RISKY = new Set([..."ntrbfv0.|[](){}+?*^<>/dswDSW:=-!,%#@~"]);
|
||||
|
||||
/* 刻意不修 `\t`:它是唯一一类「退化后无害」的转义——
|
||||
真实制表符放进 awk -F"…" / printf / cut 的结果与 \t 完全一致,而在展示型输出块里
|
||||
渲染成对齐的制表位比字面 \t 更好看。其余字符会改变语义(正则、jq 插值、jsonpath)
|
||||
或直接破坏语法(awk 字符串里的裸换行)。 */
|
||||
const SKIP = new Set(["t"]);
|
||||
|
||||
const dir = process.argv[2];
|
||||
const write = process.argv.includes("--write");
|
||||
if (!dir) { console.error("用法:node .sre-s23/fix-esc2.js <dir> [--write]"); process.exit(1); }
|
||||
|
||||
const p = path.join(DIR, dir + ".js");
|
||||
const src = fs.readFileSync(p, "utf8");
|
||||
const tick = src.indexOf("`");
|
||||
const head = src.slice(0, tick);
|
||||
const body = src.slice(tick);
|
||||
|
||||
const report = [];
|
||||
let count = 0;
|
||||
|
||||
/* 在区域内把所有风险转义双写;isTextBlock 为真时放过 \t */
|
||||
function fixRegion(text, isTextBlock, where) {
|
||||
return text.replace(/\\(.)/g, (m, ch) => {
|
||||
if (ch === "\\") return m; // \\ 已经正确
|
||||
if (ch === "x" || ch === "u") return m; // \xHH / \uHHHH 视为刻意
|
||||
if (SKIP.has(ch)) return m; // 刻意保留(见文件头)
|
||||
if (!RISKY.has(ch)) return m; // 不在风险集合里,放过
|
||||
/* 行尾 \ 由 fix-esc.js 负责;这里只处理后面还有内容的 */
|
||||
count++;
|
||||
report.push(`${where} \\${ch} → \\\\${ch}`);
|
||||
return "\\\\" + ch;
|
||||
});
|
||||
}
|
||||
|
||||
let out = "";
|
||||
let pos = 0;
|
||||
/* 逐个区域处理,区域外原样保留 */
|
||||
const re = /<pre(\s[^>]*)?>[\s\S]*?<\/pre>|<code>[\s\S]*?<\/code>/g;
|
||||
let m;
|
||||
while ((m = re.exec(body)) !== null) {
|
||||
out += body.slice(pos, m.index);
|
||||
const seg = m[0];
|
||||
const isText = /<pre[^>]*data-lang="text"/.test(seg);
|
||||
const isCode = seg.startsWith("<code>");
|
||||
/* 只处理开合标签之间的内容 */
|
||||
const inner = seg.replace(/^<pre(\s[^>]*)?>/, "").replace(/<\/pre>$/, "")
|
||||
.replace(/^<code>/, "").replace(/<\/code>$/, "");
|
||||
const fixedInner = fixRegion(inner, isText && !isCode, dir);
|
||||
out += seg.startsWith("<code>") ? "<code>" + fixedInner + "</code>"
|
||||
: seg.slice(0, seg.indexOf(">") + 1) + fixedInner + "</pre>";
|
||||
pos = m.index + seg.length;
|
||||
}
|
||||
out += body.slice(pos);
|
||||
|
||||
console.log(`${dir}:需要修复 ${count} 处`);
|
||||
report.slice(0, 20).forEach(r => console.log(" " + r));
|
||||
if (report.length > 20) console.log(` … 另 ${report.length - 20} 处`);
|
||||
|
||||
if (write && count) {
|
||||
fs.writeFileSync(p, head + out, "utf8");
|
||||
console.log("已写回");
|
||||
}
|
||||
@@ -52,7 +52,11 @@ const CHAIN = [
|
||||
["s5-02-postmortem", "复盘与根因分析", "s5"],
|
||||
["s5-03-perf", "性能分析与内核调优", "s5"],
|
||||
["s5-04-security", "安全与合规运维", "s5"],
|
||||
["s5-05-toil", "效率与 Toil 消除", "s5"]
|
||||
["s5-05-toil", "效率与 Toil 消除", "s5"],
|
||||
["s6-01-review", "架构评审与可运维性设计", "s6"],
|
||||
["s6-02-governance", "数据驱动的可靠性治理", "s6"],
|
||||
["s6-03-influence", "影响力与带人", "s6"],
|
||||
["s6-04-career", "职业路径与个人品牌", "s6"]
|
||||
];
|
||||
const STAGE_TITLE = {
|
||||
s0: "打地基", s1: "服务上线", s2: "看得见",
|
||||
@@ -214,6 +218,7 @@ function generate(m) {
|
||||
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 hasNextStage = Object.prototype.hasOwnProperty.call(STAGE_TITLE, nextStage);
|
||||
|
||||
/* ---- 模块目录页 ---- */
|
||||
const secTotal = m.chapters.reduce((n, c) =>
|
||||
@@ -240,7 +245,9 @@ function generate(m) {
|
||||
: [null, "← 上一模块", "已经是第一个模块"];
|
||||
const idxNext = nextMod
|
||||
? [`../${nextMod[0]}/index.html`, "下一模块 →", nextMod[1]]
|
||||
: [`../../index.html#${nextStage}`, "下一模块 →", `阶段 ${nextStage.slice(1)} · ${STAGE_TITLE[nextStage]}`];
|
||||
: hasNextStage
|
||||
? [`../../index.html#${nextStage}`, "下一模块 →", `阶段 ${nextStage.slice(1)} · ${STAGE_TITLE[nextStage]}`]
|
||||
: [`../../index.html`, "全部读完 →", "返回学习路径目录"];
|
||||
|
||||
const idxBody = head(`${m.title} · 阶段 ${m.stage.num} 模块 ${m.no} · SRE 从零到成熟`,
|
||||
`${m.title} 模块目录:共 ${m.chapters.length} 章、${secTotal} 个小节。`) +
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* 从生成的页面统计每个模块的章节/小节/千字,用于 README 表格 */
|
||||
const fs = require("fs"), path = require("path");
|
||||
const MOD = "knowledge/sre-learning-path/modules";
|
||||
const dirs = fs.readdirSync(MOD).filter(d => /^s[45]-/.test(d)).sort();
|
||||
const dirs = fs.readdirSync(MOD).filter(d => /^s[456]-/.test(d)).sort();
|
||||
let tCh = 0, tSec = 0, tChr = 0;
|
||||
for (const d of dirs) {
|
||||
const files = fs.readdirSync(path.join(MOD, d)).filter(f => /^\d\d-.*\.html$/.test(f)).sort();
|
||||
|
||||
39
.sre-s23/scan-detail.js
Normal file
39
.sre-s23/scan-detail.js
Normal file
@@ -0,0 +1,39 @@
|
||||
/* 详列 scan-escapes 命中的上下文,用于人工判定是否真损坏
|
||||
用法:node .sre-s23/scan-detail.js <dir> [<dir> ...]
|
||||
*/
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const DIR = path.resolve(__dirname, "content");
|
||||
|
||||
const NAMED = { n: "换行", t: "TAB", r: "回车", b: "退格", f: "换页", v: "垂直制表", "0": "NUL" };
|
||||
const DEGRADE = "+.*?$^[](){}|/dswSDW";
|
||||
|
||||
for (const name of process.argv.slice(2)) {
|
||||
const p = path.join(DIR, name + ".js");
|
||||
if (!fs.existsSync(p)) { console.log(`… ${name} 不存在`); continue; }
|
||||
const src = fs.readFileSync(p, "utf8");
|
||||
const tick = src.indexOf("`");
|
||||
const body = tick < 0 ? "" : src.slice(tick);
|
||||
const lines = body.split("\n");
|
||||
|
||||
const out = [];
|
||||
/* 逐行找,并记录是否处于 <pre>/<code> 区域内 */
|
||||
let inPre = false;
|
||||
lines.forEach((ln, i) => {
|
||||
const opens = (ln.match(/<pre[\s>]/g) || []).length;
|
||||
const closes = (ln.match(/<\/pre>/g) || []).length;
|
||||
const wasIn = inPre;
|
||||
if (opens) inPre = true;
|
||||
const here = wasIn || inPre;
|
||||
if (closes) inPre = false;
|
||||
if (!here) return;
|
||||
for (const m of ln.matchAll(/(?<!\\)\\(.)/g)) {
|
||||
const ch = m[1];
|
||||
if (ch === "\\" || ch === '"' || ch === "`" || ch === "$" ) continue;
|
||||
const s = Math.max(0, m.index - 45), e = Math.min(ln.length, m.index + 45);
|
||||
out.push(` L${i + 1} \\${ch}(${NAMED[ch] || (DEGRADE.includes(ch) ? "丢反斜杠" : "?")}) …${ln.slice(s, e).trim()}…`);
|
||||
}
|
||||
});
|
||||
if (out.length) { console.log(`\n===== ${name}(${out.length} 处,含正文区) =====`); out.slice(0, 60).forEach(l => console.log(l)); if (out.length > 60) console.log(` … 另 ${out.length - 60} 处`); }
|
||||
else console.log(`\n✓ ${name} 无命中`);
|
||||
}
|
||||
53
.sre-s23/scan-escapes.js
Normal file
53
.sre-s23/scan-escapes.js
Normal file
@@ -0,0 +1,53 @@
|
||||
/* 扫描模板字面量导致的第三类静默损坏:
|
||||
JS 在模板字面量里会解释 `\X`(X 为任意字符),因此源码里写 `\n` `\t` `\+` `\.` `\b` 等
|
||||
会被转成真实换行 / TAB / 丢反斜杠,而 fix-esc.js 只覆盖 `\"` 与行尾 `\`。
|
||||
|
||||
本脚本只报告,不修改。判读原则:
|
||||
- `<pre>` / `<code>` 内出现的这些序列,**几乎都是损坏**(命令/regex/awk 需要字面反斜杠)
|
||||
- 正文散文里出现的,通常无害(作者本意可能就是换行)
|
||||
用法:node .sre-s23/scan-escapes.js [dir ...]
|
||||
*/
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const DIR = path.resolve(__dirname, "content");
|
||||
|
||||
/* JS 会解释的转义;其余 `\X` 会退化成 X(丢反斜杠) */
|
||||
const NAMED = { n: "换行", t: "TAB", r: "回车", b: "退格(\\b 常见于正则单词边界)", f: "换页", v: "垂直制表", "0": "NUL" };
|
||||
/* 这些在 shell / regex / awk 里几乎总是想要字面反斜杠 */
|
||||
const DEGRADE = "+.*?$^[](){}|/dswSDW";
|
||||
|
||||
const targets = process.argv.slice(2).length
|
||||
? process.argv.slice(2)
|
||||
: fs.readdirSync(DIR).filter(f => f.endsWith(".js")).map(f => f.replace(/\.js$/, "")).sort();
|
||||
|
||||
let grand = 0;
|
||||
for (const name of targets) {
|
||||
const p = path.join(DIR, name + ".js");
|
||||
if (!fs.existsSync(p)) { console.log(`… ${name}:无此文件`); continue; }
|
||||
const src = fs.readFileSync(p, "utf8");
|
||||
const tick = src.indexOf("`");
|
||||
const body = tick < 0 ? "" : src.slice(tick);
|
||||
|
||||
/* 只关心代码块内的:把 <pre>...</pre> 与 <code>...</code> 内容抽出来 */
|
||||
const regions = [];
|
||||
for (const m of body.matchAll(/<pre[\s\S]*?<\/pre>/g)) regions.push(m[0]);
|
||||
for (const m of body.matchAll(/<code>[\s\S]*?<\/code>/g)) regions.push(m[0]);
|
||||
|
||||
const hits = [];
|
||||
for (const r of regions) {
|
||||
for (const m of r.matchAll(/(?<!\\)\\(.)/g)) {
|
||||
const ch = m[1];
|
||||
if (ch === "\\" || ch === '"' || ch === "`" || ch === "$" || ch === "\n") continue; // 有意转义
|
||||
hits.push({ ch, label: NAMED[ch] || (DEGRADE.includes(ch) ? "丢反斜杠" : "其它") });
|
||||
}
|
||||
}
|
||||
if (!hits.length) { console.log(`✓ ${name}:代码块内无风险转义`); continue; }
|
||||
const by = {};
|
||||
hits.forEach(h => { const k = "\\" + h.ch + " (" + h.label + ")"; by[k] = (by[k] || 0) + 1; });
|
||||
const total = hits.length;
|
||||
grand += total;
|
||||
console.log(`✗ ${name}:代码块内 ${total} 处风险转义`);
|
||||
Object.entries(by).sort((a, b) => b[1] - a[1]).slice(0, 10)
|
||||
.forEach(([k, v]) => console.log(` ${k} × ${v}`));
|
||||
}
|
||||
console.log(grand ? `\n共 ${grand} 处(需人工判断:代码块内的基本都是损坏)` : "\nOK 代码块内没有会退化的转义");
|
||||
Reference in New Issue
Block a user