Skip to main content

common_meta/
election.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub mod etcd;
16pub mod object_store;
17#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
18pub mod rds;
19
20use std::fmt::{self, Debug};
21use std::sync::Arc;
22use std::sync::atomic::{AtomicBool, Ordering};
23
24use common_telemetry::{error, info, warn};
25use serde::{Deserialize, Serialize};
26use tokio::sync::broadcast::error::RecvError;
27use tokio::sync::broadcast::{self, Receiver, Sender};
28
29use crate::error::Result;
30
31pub const CANDIDATE_LEASE_SECS: u64 = 600;
32const KEEP_ALIVE_INTERVAL_SECS: u64 = CANDIDATE_LEASE_SECS / 2;
33
34/// The value of the leader. It is used to store the leader's address.
35pub struct LeaderValue(pub String);
36
37impl<T: AsRef<[u8]>> From<T> for LeaderValue {
38    fn from(value: T) -> Self {
39        let string = String::from_utf8_lossy(value.as_ref());
40        Self(string.to_string())
41    }
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct MetasrvNodeInfo {
46    // The metasrv's address
47    pub addr: String,
48    // The node build version
49    pub version: String,
50    // The node build git commit hash
51    pub git_commit: String,
52    // The node start timestamp in milliseconds
53    pub start_time_ms: u64,
54    // The node total cpu millicores
55    #[serde(default)]
56    pub total_cpu_millicores: i64,
57    // The node total memory bytes
58    #[serde(default)]
59    pub total_memory_bytes: i64,
60    /// The node build cpu usage millicores
61    #[serde(default)]
62    pub cpu_usage_millicores: i64,
63    /// The node build memory usage bytes
64    #[serde(default)]
65    pub memory_usage_bytes: i64,
66    // The node hostname
67    #[serde(default)]
68    pub hostname: String,
69}
70
71// TODO(zyy17): Allow deprecated fields for backward compatibility. Remove this when the deprecated top-level fields are removed from the proto.
72#[allow(deprecated)]
73impl From<MetasrvNodeInfo> for api::v1::meta::MetasrvNodeInfo {
74    fn from(node_info: MetasrvNodeInfo) -> Self {
75        Self {
76            peer: Some(api::v1::meta::Peer {
77                addr: node_info.addr,
78                ..Default::default()
79            }),
80            // TODO(zyy17): The following top-level fields are deprecated. They are kept for backward compatibility and will be removed in a future version.
81            // New code should use the fields in `info.NodeInfo` instead.
82            version: node_info.version.clone(),
83            git_commit: node_info.git_commit.clone(),
84            start_time_ms: node_info.start_time_ms,
85            cpus: node_info.total_cpu_millicores as u32,
86            memory_bytes: node_info.total_memory_bytes as u64,
87            // The canonical location for node information.
88            info: Some(api::v1::meta::NodeInfo {
89                version: node_info.version,
90                git_commit: node_info.git_commit,
91                start_time_ms: node_info.start_time_ms,
92                total_cpu_millicores: node_info.total_cpu_millicores,
93                total_memory_bytes: node_info.total_memory_bytes,
94                cpu_usage_millicores: node_info.cpu_usage_millicores,
95                memory_usage_bytes: node_info.memory_usage_bytes,
96                cpus: node_info.total_cpu_millicores as u32,
97                memory_bytes: node_info.total_memory_bytes as u64,
98                hostname: node_info.hostname,
99            }),
100        }
101    }
102}
103
104/// Messages sent when the leader changes.
105#[derive(Debug, Clone)]
106pub enum LeaderChangeMessage {
107    Elected(Arc<dyn LeaderKey>),
108    StepDown(Arc<dyn LeaderKey>),
109}
110
111/// LeaderKey is a key that represents the leader of metasrv.
112/// The structure is corresponding to [etcd_client::LeaderKey].
113pub trait LeaderKey: Send + Sync + Debug {
114    /// The name in byte. name is the election identifier that corresponds to the leadership key.
115    fn name(&self) -> &[u8];
116
117    /// The key in byte. key is an opaque key representing the ownership of the election. If the key
118    /// is deleted, then leadership is lost.
119    fn key(&self) -> &[u8];
120
121    /// The creation revision of the key.
122    fn revision(&self) -> i64;
123
124    /// The lease ID of the election leader.
125    fn lease_id(&self) -> i64;
126}
127
128impl fmt::Display for LeaderChangeMessage {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        let leader_key = match self {
131            LeaderChangeMessage::Elected(leader_key) => {
132                write!(f, "Elected(")?;
133                leader_key
134            }
135            LeaderChangeMessage::StepDown(leader_key) => {
136                write!(f, "StepDown(")?;
137                leader_key
138            }
139        };
140        write!(f, "LeaderKey {{ ")?;
141        write!(f, "name: {}", String::from_utf8_lossy(leader_key.name()))?;
142        write!(f, ", key: {}", String::from_utf8_lossy(leader_key.key()))?;
143        write!(f, ", rev: {}", leader_key.revision())?;
144        write!(f, ", lease: {}", leader_key.lease_id())?;
145        write!(f, " }})")
146    }
147}
148
149fn listen_leader_change(leader_value: String) -> Sender<LeaderChangeMessage> {
150    let (tx, mut rx) = broadcast::channel(100);
151    let _handle = common_runtime::spawn_global(async move {
152        loop {
153            match rx.recv().await {
154                Ok(msg) => match msg {
155                    LeaderChangeMessage::Elected(key) => {
156                        info!(
157                            "[{leader_value}] is elected as leader: {:?}, lease: {}",
158                            String::from_utf8_lossy(key.name()),
159                            key.lease_id()
160                        );
161                    }
162                    LeaderChangeMessage::StepDown(key) => {
163                        warn!(
164                            "[{leader_value}] is stepping down: {:?}, lease: {}",
165                            String::from_utf8_lossy(key.name()),
166                            key.lease_id()
167                        );
168                    }
169                },
170                Err(RecvError::Lagged(_)) => {
171                    warn!("Log printing is too slow or leader changed too fast!");
172                }
173                Err(RecvError::Closed) => break,
174            }
175        }
176    });
177    tx
178}
179
180/// Sends a leader change message to the channel and sets the `is_leader` flag.
181/// If a leader is elected, it will also set the `leader_infancy` flag to true.
182fn send_leader_change_and_set_flags(
183    is_leader: &AtomicBool,
184    leader_infancy: &AtomicBool,
185    tx: &Sender<LeaderChangeMessage>,
186    msg: LeaderChangeMessage,
187) {
188    let is_elected = matches!(msg, LeaderChangeMessage::Elected(_));
189    if is_leader
190        .compare_exchange(!is_elected, is_elected, Ordering::AcqRel, Ordering::Acquire)
191        .is_ok()
192    {
193        if is_elected {
194            leader_infancy.store(true, Ordering::Release);
195        }
196        if let Err(e) = tx.send(msg) {
197            error!(e; "Failed to send leader change message");
198        }
199    }
200}
201
202#[async_trait::async_trait]
203pub trait Election: Send + Sync {
204    type Leader;
205
206    /// Returns `true` if current node is the leader.
207    fn is_leader(&self) -> bool;
208
209    /// When a new leader is born, it may need some initialization
210    /// operations (asynchronous), this method tells us when these
211    /// initialization operations can be performed.
212    ///
213    /// note: a new leader will only return true on the first call.
214    fn in_leader_infancy(&self) -> bool;
215
216    /// Registers a candidate for the election.
217    async fn register_candidate(&self, node_info: &MetasrvNodeInfo) -> Result<()>;
218
219    /// Gets all candidates in the election.
220    async fn all_candidates(&self) -> Result<Vec<MetasrvNodeInfo>>;
221
222    /// Campaign waits to acquire leadership in an election.
223    ///
224    /// Multiple sessions can participate in the election,
225    /// but only one can be the leader at a time.
226    async fn campaign(&self) -> Result<()>;
227
228    /// Resets the campaign.
229    ///
230    /// Reset the client and the leader flag if needed.
231    async fn reset_campaign(&self) {}
232
233    /// Returns the leader value for the current election.
234    async fn leader(&self) -> Result<Self::Leader>;
235
236    /// Releases election leadership so other campaigners may
237    /// acquire leadership on the election.
238    async fn resign(&self) -> Result<()>;
239
240    fn subscribe_leader_change(&self) -> Receiver<LeaderChangeMessage>;
241}
242
243pub type ElectionRef = Arc<dyn Election<Leader = LeaderValue>>;