sofastack / sofa-jraft

A production-grade java implementation of RAFT consensus algorithm.
https://www.sofastack.tech/projects/sofa-jraft/
Apache License 2.0
3.53k stars 1.12k forks source link

Misjudgment of obtaining leader due to time delay #1032

Closed 1294566108 closed 9 months ago

1294566108 commented 9 months ago

Describe the bug

在节点启动的过程中,可能会由于服务器自身处理速度的问题,导致调用Node#getLeaderId时会出现空指针,服务启动会存在失败的概率。这种由延迟导致的误判问题应该被修复。

Expected behavior

节点正常启动,当获取leaderId失败应该再尝试重复获取。

Steps to reproduce

在如下代码中会存在问题:

image

或许我们可以像TestCluster#waitLeader用自旋重试去不断尝试获取:

image

但是上述解决方案可能存在自旋导致阻塞的问题,因为本身getLeaderId这个方法期待一个PeerId类型的返回值。或许可以设置一个自旋阈值,每次自旋进行一个小段时间的sleep,多次尝试无果后再返回null,由此避免误判

image

Minimal yet complete reproducer code (or GitHub URL to code)

killme2008 commented 9 months ago

没明白问题是什么? getLeaderId 是有可能返回 null,这是 API 规范的一部分,这表示选举还没有完成。如果你要确保 leaderId 一定存在,那就在 StateMachine 回调里等 onLeaderStart ,记录下 leader id,然后从那边获取。