1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use kvproto::metapb::Region;
use pd_client::{Feature, FeatureGate};
use serde_derive::{Deserialize, Serialize};
const NEGOTIATION_HIBERNATE: Feature = Feature::require(5, 0, 0);
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum GroupState {
Ordered,
Chaos,
PreChaos,
Idle,
}
#[derive(PartialEq, Debug)]
pub enum LeaderState {
Awaken,
Poll(Vec<u64>),
Hibernated,
}
#[derive(Debug)]
pub struct HibernateState {
group: GroupState,
leader: LeaderState,
}
impl HibernateState {
pub fn ordered() -> HibernateState {
HibernateState {
group: GroupState::Ordered,
leader: LeaderState::Awaken,
}
}
pub fn group_state(&self) -> GroupState {
self.group
}
pub fn reset(&mut self, group_state: GroupState) {
self.group = group_state;
if group_state != GroupState::Idle {
self.leader = LeaderState::Awaken;
}
}
pub fn count_vote(&mut self, from: u64) {
if let LeaderState::Poll(v) = &mut self.leader {
if !v.contains(&from) {
v.push(from);
}
}
}
pub fn should_bcast(&self, gate: &FeatureGate) -> bool {
gate.can_enable(NEGOTIATION_HIBERNATE)
}
pub fn maybe_hibernate(&mut self, my_id: u64, region: &Region) -> bool {
let peers = region.get_peers();
let v = match &mut self.leader {
LeaderState::Awaken => {
self.leader = LeaderState::Poll(Vec::with_capacity(peers.len()));
return false;
}
LeaderState::Poll(v) => v,
LeaderState::Hibernated => return true,
};
if v.len() + 1 < peers.len() {
return false;
}
if peers
.iter()
.all(|p| p.get_id() == my_id || v.contains(&p.get_id()))
{
self.leader = LeaderState::Hibernated;
true
} else {
false
}
}
}