rust-etcd-utils 0.13.0

A set of utilities for working with etcd in Rust.
Documentation
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use {
    crate::retry::retry_etcd,
    futures::StreamExt,
    std::time::Duration,
    tokio::{
        sync::{broadcast, mpsc, oneshot},
        task::{JoinHandle, JoinSet},
        time::Instant,
    },
    tracing::{error, warn},
};

// Jiffy is interval between system timer interrupts, typically 10ms for linux systems.
const AT_LEAST_10_JIFFIES: Duration = Duration::from_millis(100);

///
/// Managed lease instance that will keep the lease alive until it is dropped.
///
/// See [`ManagedLeaseFactory::new_lease`] for more information.
///
pub struct ManagedLease {
    etcd: etcd_client::Client,
    pub lease_id: i64,
    // Let this field dead, because when drop it will trigger a task to wake up and gracefully revoke lease.
    #[allow(dead_code)]
    _tx_terminate: oneshot::Sender<()>,

    rx_lease_expire: broadcast::Receiver<()>,
}

///
/// Weak reference to the managed lease.
///
/// This can be used to check if the lease is still alive.
/// The reference is weak because dropping this reference will not revoke the lease.
pub struct ManagedLeaseWeak {
    lease_id: i64,
    etcd: etcd_client::Client,
    rx_lease_expire: broadcast::Receiver<()>,
}

impl ManagedLeaseWeak {
    pub fn lease_id(&self) -> i64 {
        self.lease_id
    }

    pub fn get_lease_expire_notify(&self) -> LeaseExpiredNotify {
        LeaseExpiredNotify {
            inner: self.rx_lease_expire.resubscribe(),
        }
    }

    pub async fn is_alive(&self) -> Result<bool, etcd_client::Error> {
        let result = retry_etcd(
            self.etcd.clone(),
            (self.lease_id,),
            |etcd, (lease_id,)| async move {
                let resp = etcd.lease_client().time_to_live(lease_id, None).await?;
                Ok(resp.ttl() > 0)
            },
        )
        .await;

        match result {
            Ok(is_alive) => Ok(is_alive),
            Err(e) => match e {
                etcd_client::Error::GRpcStatus(status) => {
                    if status.code() == tonic::Code::NotFound {
                        Ok(false)
                    } else {
                        Err(etcd_client::Error::GRpcStatus(status))
                    }
                }
                _ => Err(e),
            },
        }
    }
}

impl ManagedLease {
    pub fn lease_id(&self) -> i64 {
        self.lease_id
    }

    pub fn get_lease_expire_notify(&self) -> LeaseExpiredNotify {
        LeaseExpiredNotify {
            inner: self.rx_lease_expire.resubscribe(),
        }
    }

    pub async fn is_alive(&self) -> Result<bool, etcd_client::Error> {
        let result = retry_etcd(
            self.etcd.clone(),
            (self.lease_id,),
            |etcd, (lease_id,)| async move {
                let resp = etcd.lease_client().time_to_live(lease_id, None).await?;
                Ok(resp.ttl() > 0)
            },
        )
        .await;

        match result {
            Ok(is_alive) => Ok(is_alive),
            Err(e) => match e {
                etcd_client::Error::GRpcStatus(status) => {
                    if status.code() == tonic::Code::NotFound {
                        Ok(false)
                    } else {
                        Err(etcd_client::Error::GRpcStatus(status))
                    }
                }
                _ => Err(e),
            },
        }
    }

    pub fn get_weak(&self) -> ManagedLeaseWeak {
        ManagedLeaseWeak {
            lease_id: self.lease_id,
            etcd: self.etcd.clone(),
            rx_lease_expire: self.rx_lease_expire.resubscribe(),
        }
    }
}

///
/// Managed lease factory that will create a new lease and keep it alive until it is dropped.
///
#[derive(Clone)]
pub struct ManagedLeaseFactory {
    cnc_tx: mpsc::Sender<ManagedLeaseRuntimeCommand>,
}

///
/// Notify when the lease has expired.
///
pub struct LeaseExpiredNotify {
    inner: broadcast::Receiver<()>,
}

impl LeaseExpiredNotify {
    ///
    /// Wait until the lease has expired.
    ///
    pub async fn recv(mut self) {
        let _ = self.inner.recv().await;
    }
}

impl Clone for LeaseExpiredNotify {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.resubscribe(),
        }
    }
}

struct CreateLeaseCommand {
    ttl: Duration,
    keepalive_interval: Option<Duration>,
    auto_refresh_limit: Option<usize>,
    callback: oneshot::Sender<Result<ManagedLease, CreateLeaseError>>,
}

enum ManagedLeaseRuntimeCommand {
    CreateLease(CreateLeaseCommand),
}

///
/// Managed lease factory runtime that will handle the lease creation and keep alive.
/// This is a separate task that will run in the background.
///
struct ManagedLeaseFactoryRuntime {
    ///
    /// The etcd client to use.
    ///
    etcd: etcd_client::Client,

    ///
    /// The runtime handle to spawn tasks on.
    ///
    rt: tokio::runtime::Handle,

    ///
    /// The join set to manage the tasks.
    ///
    js: JoinSet<()>,

    ///
    /// The channel to notify the runtime to shutdown.
    ///
    cnc_rx: mpsc::Receiver<ManagedLeaseRuntimeCommand>,
}

#[derive(Debug, thiserror::Error)]
pub enum CreateLeaseError {
    #[error("lease creation failed")]
    EtcdError(#[from] etcd_client::Error),
    #[error("invalid lease ttl, must be at least 2 seconds")]
    InvalidTTL,
}

impl ManagedLeaseFactoryRuntime {
    async fn handle_create_lease(&mut self, cmd: CreateLeaseCommand) {
        let CreateLeaseCommand {
            ttl,
            keepalive_interval,
            auto_refresh_limit,
            callback,
        } = cmd;
        let ttl_secs = ttl.as_secs() as i64;
        let lease_result = retry_etcd(self.etcd.clone(), (), move |mut etcd, _| async move {
            etcd.lease_grant(ttl_secs, None).await
        })
        .await;
        let lease_id = match lease_result {
            Ok(lease) => lease.id(),
            Err(e) => {
                let _ = callback.send(Err(e.into()));
                return;
            }
        };
        let (stop_tx, mut stop_rx) = oneshot::channel::<()>();
        let client = self.etcd.clone();
        let (tx_expired, rx_expired) = broadcast::channel(1);
        let _ah = self.js.spawn_on(async move {
            let mut refresh_count = 0;
            'outer: loop {
                let first_keep_alive  = Instant::now();
                let (mut keeper, mut keep_alive_resp_stream) = retry_etcd(
                    client.clone(),
                    (lease_id,),
                    move |mut client, (lease_id,)| {
                        async move {
                            client.lease_keep_alive(lease_id).await
                        }
                    })
                        .await
                        .expect("failed to keep alive lease");  // if we have an error this will break out the entire loop
                let mut last_keep_alive = first_keep_alive;
                let keepalive_interval =
                    keepalive_interval.unwrap_or(Duration::from_secs((ttl_secs / 2) as u64));
                let mut next_renewal = first_keep_alive + keepalive_interval;
                'inner: loop {

                    if let Some(limit) = auto_refresh_limit {
                        if refresh_count >= limit {
                            warn!("auto refresh limit reached, stopping lease {lease_id:?} after {refresh_count} refreshes");
                            break 'outer;
                        }
                    }

                    tokio::select! {
                        _ = tokio::time::sleep_until(next_renewal) => {
                            let since_last_keep_alive = last_keep_alive.elapsed();
                            if since_last_keep_alive > keepalive_interval {
                                let dt = since_last_keep_alive - keepalive_interval;
                                if dt >= AT_LEAST_10_JIFFIES {
                                    warn!("last keep alive was {dt:?} late");
                                }
                            }
                            if let Err(e) = keeper.keep_alive().await {
                                error!("failed to keep alive lease {lease_id:?}, got {e:?}");
                                break 'inner;
                            }
                            last_keep_alive = Instant::now();
                            next_renewal += keepalive_interval;
                            let res = keep_alive_resp_stream.next().await;
                            match res {
                                Some(Ok(keep_alive_resp)) => {
                                    refresh_count += 1;
                                    if keep_alive_resp.ttl() == 0 {
                                        error!("lease {lease_id:?} expired");
                                        break 'outer;
                                    }
                                    let ttl = keep_alive_resp.ttl();
                                    if ttl < ttl_secs {
                                        warn!("lease {lease_id:?} ttl reduced to {ttl}, since_last_keep_alive: {since_last_keep_alive:?}");
                                    }
                                    tracing::trace!("keep alive lease {lease_id:?} at {since_last_keep_alive:?}");
                                }
                                Some(Err(e)) => {
                                    warn!("keep alive stream for lease {lease_id:?} errored: {e:?}");
                                    break 'inner;
                                }
                                None => {
                                    warn!("keep alive stream for lease {lease_id:?} ended");
                                    break 'inner;
                                }
                            }
                        }
                        _ = &mut stop_rx => {
                            let since_last_keep_alive = last_keep_alive.elapsed();
                            tracing::info!("revoking lease {lease_id:?}, last keep alive: {since_last_keep_alive:?}");
                            let result = retry_etcd(
                                client.clone(),
                                (lease_id,),
                                move |mut client, (lease_id,)| {
                                    async move {
                                        match client.lease_revoke(lease_id).await {
                                            Ok(_) => Ok(()),
                                            Err(etcd_client::Error::GRpcStatus(status)) => {
                                                if status.code() == tonic::Code::NotFound {
                                                    tracing::warn!("lease {lease_id:?} was already deleted");
                                                    Ok(())
                                                } else {
                                                    Err(etcd_client::Error::GRpcStatus(status))
                                                }
                                            }
                                            Err(e) => Err(e),
                                        }
                                    }
                                }
                            );
                            if let Err(e) = result.await {
                                error!("failed to revoke lease {lease_id:?}, got {e:?}");
                            }
                            break 'outer;
                        }
                    }
                }
            }
            let _ = tx_expired.send(());
        }, &self.rt);
        let lease = ManagedLease {
            etcd: self.etcd.clone(),
            lease_id,
            _tx_terminate: stop_tx,
            rx_lease_expire: rx_expired,
        };
        let _ = callback.send(Ok(lease));
    }

    async fn handle_command(&mut self, cmd: ManagedLeaseRuntimeCommand) {
        match cmd {
            ManagedLeaseRuntimeCommand::CreateLease(cmd) => {
                self.handle_create_lease(cmd).await;
            }
        }
    }

    async fn run(mut self) {
        loop {
            // Loops ends when both the command channel and the join set are closed.
            // When command-and-control channel is closed, it means no `ManagedLease` exists anymore.
            // However, the join set may still have tasks running, we must wait for them to finish.
            tokio::select! {
                Some(cmd) = self.cnc_rx.recv() => {
                    self.handle_command(cmd).await;
                }
                Some(res) = self.js.join_next() => {
                    match res {
                        Ok(_) => {
                            // task completed successfully
                            tracing::trace!("managed lease task completed");
                        }
                        Err(e) => {
                            tracing::warn!("task failed: {e:?}");
                        }
                    }
                }
                else => {
                    break;
                }
            }
        }
        tracing::trace!("managed lease factory runtime exiting");
    }
}

impl ManagedLeaseFactory {
    ///
    /// Create a new managed lease factory.
    /// This will spawn a new task that will handle the lease creation and keep alive.
    ///
    pub fn spawn(etcd: etcd_client::Client) -> (Self, JoinHandle<()>) {
        Self::spawn_on(etcd, tokio::runtime::Handle::current())
    }

    ///
    /// Create a new managed lease factory.
    /// This will spawn a new task that will handle the lease creation and keep alive.
    ///
    /// Arguments:
    /// * `etcd` - The etcd client to use.
    /// * `rt` - The runtime handle to spawn tasks on.
    pub fn spawn_on(
        etcd: etcd_client::Client,
        rt: tokio::runtime::Handle,
    ) -> (Self, JoinHandle<()>) {
        let (cnc_tx, cnc_rx) = mpsc::channel(100);
        let lease_rt = ManagedLeaseFactoryRuntime {
            etcd,
            rt: rt.clone(),
            js: JoinSet::new(),
            cnc_rx,
        };
        let jh = rt.spawn(lease_rt.run());
        (
            Self {
                cnc_tx: cnc_tx.clone(),
            },
            jh,
        )
    }

    ///
    /// Create a new managed lease with the given time-to-live (TTL), keepalive interval and auto refresh limit.
    /// The lease will be kept alive until it is dropped OR until the lease has been refresh `auto_refresh_limit` times.
    ///
    /// Arguments:
    ///
    /// * `ttl` - The time-to-live for the lease.
    /// * `keepalive_interval` - The interval to keep the lease alive.
    /// * `auto_refresh_limit` - The number of times to auto refresh the lease.
    ///
    pub async fn new_lease_with_auto_refresh_limit(
        &self,
        ttl: Duration,
        keepalive_interval: Option<Duration>,
        auto_refresh_limit: Option<usize>,
    ) -> Result<ManagedLease, etcd_client::Error> {
        let ttl_secs: i64 = ttl.as_secs() as i64;
        assert!(ttl_secs >= 2, "lease ttl must be at least two (2) seconds");
        let (callback_tx, callback_rx) = oneshot::channel();
        let command = CreateLeaseCommand {
            ttl,
            keepalive_interval,
            auto_refresh_limit,
            callback: callback_tx,
        };
        self.cnc_tx
            .send(ManagedLeaseRuntimeCommand::CreateLease(command))
            .await
            .expect("failed to send command to managed lease factory");

        let result = callback_rx
            .await
            .expect("failed to receive result from managed lease factory");
        match result {
            Ok(lease) => Ok(lease),
            Err(e) => match e {
                CreateLeaseError::EtcdError(e) => Err(e),
                CreateLeaseError::InvalidTTL => {
                    panic!("lease ttl must be at least two (2) seconds");
                }
            },
        }
    }

    ///
    /// Create a new managed lease with the given time-to-live (TTL) and keepalive interval.
    ///
    /// Managed lease have automatic keep alive mechanism that will keep the lease alive until it is dropped.
    ///
    /// The ttl must be at least two (2) seconds.
    ///
    /// Keepalive interval is optional, if not provided it will be half of the ttl.
    ///
    /// Arguments:
    ///
    /// * `ttl` - The time-to-live for the lease.
    /// * `keepalive_interval` - The interval to keep the lease alive.
    ///
    pub async fn new_lease(
        &self,
        ttl: Duration,
        keepalive_interval: Option<Duration>,
    ) -> Result<ManagedLease, etcd_client::Error> {
        self.new_lease_with_auto_refresh_limit(ttl, keepalive_interval, None)
            .await
    }
}