如何注入磁盘损坏并验证 CheckIndex 修复结果

解读

在国内一线互联网公司的搜索团队面试中,这道题常被用来区分“只看过文档”与“真正调过 Lucene 源码”的候选人。
面试官期望你回答三个层次:

  1. 能在 不破坏宿主机文件系统 的前提下,精准注入 Lucene 索引的物理损坏;
  2. 能解释 CheckIndex 的修复策略 与 局限性;
  3. 能给出 可落地的自动化验证脚本,并说明如何集成到 CI,防止“修复后静默丢数据”。

知识点

  1. Lucene 索引物理结构:segments_N、.cfs、.fdx、.fdt、.tim、.tip、.doc、.pos、.pay 等文件各司其职,损坏点不同,症状不同。
  2. 三种注入手段:
    • 字节级篡改:用 dd/hexedit 随机写坏 checksum 或 codec header 魔数;
    • truncation:truncate -s -100 直接砍掉文件尾部,模拟磁盘满或掉电;
    • JVM 层注入:在 FSDirectory 子类里重写 writeByte/readByte,按概率抛 IOException 或返回 0xFF,可重复、无需 root。
  3. CheckIndex 执行链:CheckIndex.Status → SegmentInfo → FieldInfo → TermVector → PointValues → SortedDocValues 逐级校验;发现错误后,仅对“可自我恢复”的段生成新的 segments_N,不会自动修复原始损坏文件。
  4. 修复结果验证:
    • 零数据丢失:对比损坏前与修复后 IndexReader.numDocs()、TermEnum 总数、PointValues.size();
    • 语义一致性:用提前导出的 golden term–docId 集合 做 assertEquals;
    • 性能回退:观察 IndexSearcher.search 99th latency 是否因段合并策略改变而劣化。
  5. 国内合规注意:生产环境磁盘损坏演练需走 “蓝绿/影子集群” 报备,禁止直接在生产主机 dd 写盘,否则触碰《网络安全法》第 21 条“不得危害网络运行安全”。

答案

步骤一:构建最小可重复索引

# 写入 10 万条微博文本,开启 compound 格式,生成单 segment
curl -X POST http://localhost:8080/index -d '{"analyzer":"ik_max_word","docs":100000}'

步骤二:JVM 层注入损坏(无需 root,可单元测试内嵌)

public class CorruptDirectory extends FilterDirectory {
    final Random rnd = new Random(42);
    public CorruptDirectory(Directory in) { super(in); }
    @Override public IndexInput openInput(String name, IOContext ctx) throws IOException {
        return new CorruptInput(super.openInput(name, ctx));
    }
    static class CorruptInput extends IndexInput {
        IndexInput delegate;
        CorruptInput(IndexInput in) { delegate = in; }
        @Override public byte readByte() throws IOException {
            if (rnd.nextInt(10000) == 0) return (byte) 0xFF; // 随机 bit 翻转
            return delegate.readByte();
        }
        // 其余方法委托
    }
}

步骤三:触发 CheckIndex 并捕获结果

Directory dir = new CorruptDirectory(FSDirectory.open(Paths.get("/data/index")));
CheckIndex checker = new CheckIndex(dir);
checker.setInfoStream(System.out); // 打印详细报告,方便面试时讲思路
CheckIndex.Status st = checker.checkIndex();
if (!st.clean) {
    if (checker.fixIndex(st)) { // 返回 true 表示修复成功
        System.out.println("修复后 segments=" + st.segmentInfos.size());
    }
}

步骤四:验证零数据丢失

// 损坏前已把 term→docId 的 golden set 序列化到文件
Set<String> before = readGoldenSet();
Directory repaired = FSDirectory.open(Paths.get("/data/index"));
IndexReader reader = DirectoryReader.open(repaired);
Set<String> after = new HashSet<>();
TermsEnum te = MultiTerms.getTerms(reader, "text").iterator();
while (te.next() != null) {
    after.add(te.term().utf8ToString());
}
assert before.equals(after) : "存在 term 级丢数据";
assert reader.numDocs() == 100000 : "文档数不一致";

步骤五:集成到 GitLab CI(国内主流)

lucene-corrupt-test:
  stage: stress
  script:
    - mvn test -Dtest=CorruptAndCheckIndexIT
    - ./scripts/verify_zero_data_loss.sh
  artifacts:
    reports:
      junit: target/surefire-reports/*.xml

若 verify_zero_data_loss.sh 返回非 0,则 MR 禁止合并,满足 “代码即文档、演练即测试” 的国内工程规范。

拓展思考

  1. 仅修复 segments_N 而保留损坏文件 会带来“幽灵空间”问题,可写定时任务调用 IndexWriter.forceMerge(1) 配合 setUseCompoundFile(true) 做 物理空间回收,避免 SSD 写放大。
  2. 对 多副本分布式场景(Elasticsearch),单节点 CheckIndex 修复后,还需触发 /_cluster/reroute?retry_failed=true 让主分片重新分配,否则集群状态仍 RED;面试时可主动提到这一跨进程联动,体现“不止懂 Lucene,还懂上层系统”。
  3. 国内信创环境 常用国产 ARM+麒麟 OS,磁盘损坏模拟工具 dd 参数与 x86 略有差异(bs=512 对齐),需在答案中强调 “已在鲲鹏 920 验证”,展示对国产化平台的适配经验,容易拿到加分。