meta_srv/election/
etcd.rs

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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use common_meta::distributed_time_constants::{META_KEEP_ALIVE_INTERVAL_SECS, META_LEASE_SECS};
use common_telemetry::{error, info, warn};
use etcd_client::{
    Client, GetOptions, LeaderKey as EtcdLeaderKey, LeaseKeepAliveStream, LeaseKeeper, PutOptions,
};
use snafu::{ensure, OptionExt, ResultExt};
use tokio::sync::broadcast;
use tokio::sync::broadcast::Receiver;
use tokio::time::{timeout, MissedTickBehavior};

use crate::election::{
    listen_leader_change, Election, LeaderChangeMessage, LeaderKey, CANDIDATES_ROOT,
    CANDIDATE_LEASE_SECS, ELECTION_KEY, KEEP_ALIVE_INTERVAL_SECS,
};
use crate::error;
use crate::error::Result;
use crate::metasrv::{ElectionRef, LeaderValue, MetasrvNodeInfo};

impl LeaderKey for EtcdLeaderKey {
    fn name(&self) -> &[u8] {
        self.name()
    }

    fn key(&self) -> &[u8] {
        self.key()
    }

    fn revision(&self) -> i64 {
        self.rev()
    }

    fn lease_id(&self) -> i64 {
        self.lease()
    }
}

pub struct EtcdElection {
    leader_value: String,
    client: Client,
    is_leader: AtomicBool,
    infancy: AtomicBool,
    leader_watcher: broadcast::Sender<LeaderChangeMessage>,
    store_key_prefix: String,
}

impl EtcdElection {
    pub async fn with_endpoints<E, S>(
        leader_value: E,
        endpoints: S,
        store_key_prefix: String,
    ) -> Result<ElectionRef>
    where
        E: AsRef<str>,
        S: AsRef<[E]>,
    {
        let client = Client::connect(endpoints, None)
            .await
            .context(error::ConnectEtcdSnafu)?;

        Self::with_etcd_client(leader_value, client, store_key_prefix).await
    }

    pub async fn with_etcd_client<E>(
        leader_value: E,
        client: Client,
        store_key_prefix: String,
    ) -> Result<ElectionRef>
    where
        E: AsRef<str>,
    {
        let leader_value: String = leader_value.as_ref().into();
        let tx = listen_leader_change(leader_value.clone());
        Ok(Arc::new(Self {
            leader_value,
            client,
            is_leader: AtomicBool::new(false),
            infancy: AtomicBool::new(false),
            leader_watcher: tx,
            store_key_prefix,
        }))
    }

    fn election_key(&self) -> String {
        format!("{}{}", self.store_key_prefix, ELECTION_KEY)
    }

    fn candidate_root(&self) -> String {
        format!("{}{}", self.store_key_prefix, CANDIDATES_ROOT)
    }

    fn candidate_key(&self) -> String {
        format!("{}{}", self.candidate_root(), self.leader_value)
    }
}

#[async_trait::async_trait]
impl Election for EtcdElection {
    type Leader = LeaderValue;

    fn is_leader(&self) -> bool {
        self.is_leader.load(Ordering::Relaxed)
    }

    fn in_leader_infancy(&self) -> bool {
        self.infancy
            .compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed)
            .is_ok()
    }

    async fn register_candidate(&self, node_info: &MetasrvNodeInfo) -> Result<()> {
        let mut lease_client = self.client.lease_client();
        let res = lease_client
            .grant(CANDIDATE_LEASE_SECS as i64, None)
            .await
            .context(error::EtcdFailedSnafu)?;
        let lease_id = res.id();

        // The register info: key is the candidate key, value is its node info(addr, version, git_commit).
        let key = self.candidate_key().into_bytes();
        let value = serde_json::to_string(node_info)
            .with_context(|_| error::SerializeToJsonSnafu {
                input: format!("{node_info:?}"),
            })?
            .into_bytes();
        // Puts with the lease id
        self.client
            .kv_client()
            .put(key, value, Some(PutOptions::new().with_lease(lease_id)))
            .await
            .context(error::EtcdFailedSnafu)?;

        let (mut keeper, mut receiver) = lease_client
            .keep_alive(lease_id)
            .await
            .context(error::EtcdFailedSnafu)?;

        let mut keep_alive_interval =
            tokio::time::interval(Duration::from_secs(KEEP_ALIVE_INTERVAL_SECS));

        loop {
            let _ = keep_alive_interval.tick().await;
            keeper.keep_alive().await.context(error::EtcdFailedSnafu)?;

            if let Some(res) = receiver.message().await.context(error::EtcdFailedSnafu)? {
                if res.ttl() <= 0 {
                    warn!("Candidate lease expired, key: {}", self.candidate_key());
                    break;
                }
            }
        }

        Ok(())
    }

    async fn all_candidates(&self) -> Result<Vec<MetasrvNodeInfo>> {
        let key = self.candidate_root().into_bytes();
        let res = self
            .client
            .kv_client()
            .get(key, Some(GetOptions::new().with_prefix()))
            .await
            .context(error::EtcdFailedSnafu)?;

        let mut nodes = Vec::with_capacity(res.kvs().len());
        for kv in res.kvs() {
            let node =
                serde_json::from_slice::<MetasrvNodeInfo>(kv.value()).with_context(|_| {
                    error::DeserializeFromJsonSnafu {
                        input: String::from_utf8_lossy(kv.value()),
                    }
                })?;
            nodes.push(node);
        }

        Ok(nodes)
    }

    async fn campaign(&self) -> Result<()> {
        let mut lease_client = self.client.lease_client();
        let mut election_client = self.client.election_client();
        let res = lease_client
            .grant(META_LEASE_SECS as i64, None)
            .await
            .context(error::EtcdFailedSnafu)?;
        let lease_id = res.id();

        info!("Election grant ttl: {:?}, lease: {:?}", res.ttl(), lease_id);

        // Campaign, waits to acquire leadership in an election, returning
        // a LeaderKey representing the leadership if successful.
        //
        // The method will be blocked until the election is won, and after
        // passing the method, it is necessary to execute `keep_alive` immediately
        // to confirm that it is a valid leader, because it is possible that the
        // election's lease expires.
        let res = election_client
            .campaign(self.election_key(), self.leader_value.clone(), lease_id)
            .await
            .context(error::EtcdFailedSnafu)?;

        if let Some(leader) = res.leader() {
            let (mut keeper, mut receiver) = lease_client
                .keep_alive(lease_id)
                .await
                .context(error::EtcdFailedSnafu)?;

            let keep_lease_duration = Duration::from_secs(META_KEEP_ALIVE_INTERVAL_SECS);
            let mut keep_alive_interval = tokio::time::interval(keep_lease_duration);
            keep_alive_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
            loop {
                // The keep alive operation MUST be done in `META_KEEP_ALIVE_INTERVAL_SECS`.
                match timeout(
                    keep_lease_duration,
                    self.keep_alive(&mut keeper, &mut receiver, leader.clone()),
                )
                .await
                {
                    Ok(Ok(())) => {
                        let _ = keep_alive_interval.tick().await;
                    }
                    Ok(Err(err)) => {
                        error!(err; "Failed to keep alive");
                        break;
                    }
                    Err(_) => {
                        error!("Refresh lease timeout");
                        break;
                    }
                }
            }

            if self
                .is_leader
                .compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed)
                .is_ok()
            {
                if let Err(e) = self
                    .leader_watcher
                    .send(LeaderChangeMessage::StepDown(Arc::new(leader.clone())))
                {
                    error!(e; "Failed to send leader change message");
                }
            }
        }

        Ok(())
    }

    async fn leader(&self) -> Result<LeaderValue> {
        if self.is_leader.load(Ordering::Relaxed) {
            Ok(self.leader_value.as_bytes().into())
        } else {
            let res = self
                .client
                .election_client()
                .leader(self.election_key())
                .await
                .context(error::EtcdFailedSnafu)?;
            let leader_value = res.kv().context(error::NoLeaderSnafu)?.value();
            Ok(leader_value.into())
        }
    }

    async fn resign(&self) -> Result<()> {
        todo!()
    }

    fn subscribe_leader_change(&self) -> Receiver<LeaderChangeMessage> {
        self.leader_watcher.subscribe()
    }
}

impl EtcdElection {
    async fn keep_alive(
        &self,
        keeper: &mut LeaseKeeper,
        receiver: &mut LeaseKeepAliveStream,
        leader: EtcdLeaderKey,
    ) -> Result<()> {
        keeper.keep_alive().await.context(error::EtcdFailedSnafu)?;
        if let Some(res) = receiver.message().await.context(error::EtcdFailedSnafu)? {
            ensure!(
                res.ttl() > 0,
                error::UnexpectedSnafu {
                    violated: "Failed to refresh the lease",
                }
            );

            // Only after a successful `keep_alive` is the leader considered official.
            if self
                .is_leader
                .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
                .is_ok()
            {
                self.infancy.store(true, Ordering::Relaxed);

                if let Err(e) = self
                    .leader_watcher
                    .send(LeaderChangeMessage::Elected(Arc::new(leader)))
                {
                    error!(e; "Failed to send leader change message");
                }
            }
        }

        Ok(())
    }
}