Skip to main content

mito2/
lease.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
15use std::collections::HashMap;
16use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
17use std::sync::{Arc, LazyLock, Mutex};
18use std::time::{Duration, Instant};
19
20use store_api::logstore::ObjectStoreWalIoPermit;
21use store_api::storage::RegionId;
22use tokio::sync::Notify;
23
24/// The instant lease deadlines count from, so that a deadline fits in an [AtomicU64].
25static LEASE_EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);
26
27pub(crate) fn lease_nanos(instant: Instant) -> u64 {
28    instant.saturating_duration_since(*LEASE_EPOCH).as_nanos() as u64
29}
30
31/// A lease deadline in nanoseconds since [LEASE_EPOCH]. It only moves forward; 0 means none.
32#[derive(Debug, Default)]
33pub(crate) struct Deadline(AtomicU64);
34
35impl Deadline {
36    pub(crate) fn extend(&self, deadline: Instant) {
37        self.0.fetch_max(lease_nanos(deadline), Ordering::Relaxed);
38    }
39
40    pub(crate) fn get(&self) -> u64 {
41        self.0.load(Ordering::Relaxed)
42    }
43}
44
45/// Lease of this node: the latest deadline of the heartbeat responses that carry region leases.
46#[derive(Debug, Default)]
47pub(crate) struct NodeLease {
48    /// Whether writes need a lease. Only a datanode the metasrv controls sets it.
49    enabled: AtomicBool,
50    deadline: Deadline,
51    /// The time of the lease checks while a test freezes it, in the unit of [Deadline]; 0 when
52    /// it is not frozen.
53    #[cfg(any(test, feature = "test"))]
54    frozen_now: AtomicU64,
55}
56
57impl NodeLease {
58    pub(crate) fn enable(&self) {
59        self.enabled.store(true, Ordering::Relaxed);
60    }
61
62    pub(crate) fn is_enabled(&self) -> bool {
63        self.enabled.load(Ordering::Relaxed)
64    }
65
66    pub(crate) fn renew(&self, deadline: Instant) {
67        self.deadline.extend(deadline);
68    }
69
70    /// Returns whether the deadline of this node has passed.
71    pub(crate) fn is_expired(&self) -> bool {
72        self.now() >= self.deadline.get()
73    }
74
75    /// Returns the current time in the unit of [Deadline].
76    pub(crate) fn now(&self) -> u64 {
77        #[cfg(any(test, feature = "test"))]
78        {
79            let frozen_now = self.frozen_now.load(Ordering::Relaxed);
80            if frozen_now != 0 {
81                return frozen_now;
82            }
83        }
84        lease_nanos(Instant::now())
85    }
86
87    #[cfg(any(test, feature = "test"))]
88    pub(crate) fn freeze_clock(&self, at: Instant) {
89        self.frozen_now
90            .store(lease_nanos(at).max(1), Ordering::Relaxed);
91    }
92
93    /// Lets a region created or upgraded on this node write until the node's deadline. The
94    /// metasrv granted that deadline before the creation or upgrade, so a later migration of the
95    /// region waits past it. Later responses do not extend it; the region's Leader grants do.
96    pub(crate) fn seed(&self, leader_deadline: &Deadline) {
97        leader_deadline
98            .0
99            .fetch_max(self.deadline.get(), Ordering::Relaxed);
100    }
101}
102
103/// A region lease the metasrv granted for a heartbeat sent at `sent_at`.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub(crate) struct GrantedLease {
106    pub(crate) candidate_lease_id: Option<u64>,
107    /// When the heartbeat request for which this lease was granted was sent.
108    pub(crate) sent_at: Instant,
109}
110
111impl GrantedLease {
112    /// Returns, for a lease of a heartbeat sent after `after`, whether it is the lease of
113    /// candidate `candidate_lease_id`, with the reason if not; None for an earlier lease.
114    pub(crate) fn of_candidate_after(
115        &self,
116        candidate_lease_id: u64,
117        after: Instant,
118    ) -> Option<Result<(), String>> {
119        (self.sent_at > after).then(|| {
120            if self.candidate_lease_id == Some(candidate_lease_id) {
121                Ok(())
122            } else {
123                Err(format!(
124                    "a lease sent after the catchup began carries candidate lease id {:?}",
125                    self.candidate_lease_id
126                ))
127            }
128        })
129    }
130}
131
132/// The lease of the latest heartbeat each region received, whether or not the region applied it.
133/// It is kept apart from the region instance, so a reopen during catchup keeps it.
134#[derive(Debug, Default)]
135pub(crate) struct GrantedLeases(Mutex<GrantedLeasesInner>);
136
137#[derive(Debug, Default)]
138struct GrantedLeasesInner {
139    leases: HashMap<RegionId, GrantedLease>,
140    /// Wakes the waiter of a region's candidate lease when its lease is recorded or removed. It
141    /// is empty unless a catchup waits; a lookup in an empty map returns before hashing, so a
142    /// record then costs one more length check. A region has one waiter, as the worker runs one
143    /// catchup of a region at a time.
144    waiters: HashMap<RegionId, Arc<Notify>>,
145}
146
147impl GrantedLeasesInner {
148    fn wake(&self, region_id: RegionId) {
149        if let Some(waiter) = self.waiters.get(&region_id) {
150            waiter.notify_one();
151        }
152    }
153}
154
155/// Removes the waiter of a region from [GrantedLeases] when dropped.
156struct LeaseWaiter<'a> {
157    leases: &'a GrantedLeases,
158    region_id: RegionId,
159    notify: Arc<Notify>,
160}
161
162impl Drop for LeaseWaiter<'_> {
163    fn drop(&mut self) {
164        self.leases
165            .0
166            .lock()
167            .unwrap()
168            .waiters
169            .remove(&self.region_id);
170    }
171}
172
173impl GrantedLeases {
174    /// Records the lease if `region_is_open` holds. The check runs under the same lock as
175    /// [Self::remove], which a worker calls after it removes the region, so a lease recorded
176    /// concurrently with the removal does not outlive it.
177    pub(crate) fn record(
178        &self,
179        region_id: RegionId,
180        sent_at: Instant,
181        candidate_lease_id: Option<u64>,
182        region_is_open: impl FnOnce() -> bool,
183    ) {
184        let lease = GrantedLease {
185            candidate_lease_id,
186            sent_at,
187        };
188        let mut inner = self.0.lock().unwrap();
189        if !region_is_open() {
190            return;
191        }
192        inner
193            .leases
194            .entry(region_id)
195            .and_modify(|latest| {
196                if sent_at > latest.sent_at {
197                    *latest = lease;
198                }
199            })
200            .or_insert(lease);
201        inner.wake(region_id);
202    }
203
204    pub(crate) fn remove(&self, region_id: RegionId) {
205        let mut inner = self.0.lock().unwrap();
206        inner.leases.remove(&region_id);
207        inner.wake(region_id);
208    }
209
210    pub(crate) fn get(&self, region_id: RegionId) -> Option<GrantedLease> {
211        self.0.lock().unwrap().leases.get(&region_id).copied()
212    }
213
214    /// Returns whether a catchup waits for the candidate lease of the region.
215    #[cfg(test)]
216    pub(crate) fn is_waiting(&self, region_id: RegionId) -> bool {
217        self.0.lock().unwrap().waiters.contains_key(&region_id)
218    }
219
220    fn register(&self, region_id: RegionId) -> LeaseWaiter<'_> {
221        let notify = Arc::new(Notify::new());
222        self.0
223            .lock()
224            .unwrap()
225            .waiters
226            .insert(region_id, notify.clone());
227        LeaseWaiter {
228            leases: self,
229            region_id,
230            notify,
231        }
232    }
233
234    /// Waits until region `region_id` records the lease of a heartbeat sent after `after`; send
235    /// times have millisecond precision. Returns `Ok(())` only if that lease carries
236    /// `candidate_lease_id`, and fails with the reason as soon as a lease sent after `after`
237    /// carries another candidate lease id or none. Also fails with the reason if `is_stopped`
238    /// holds, or if the lease of this node, `node_lease`, expires before such a lease is recorded.
239    ///
240    /// The wait has no bound of its own: every reply to a heartbeat sent after `after` records a
241    /// lease of the region, or, once the migration ends, the metasrv closes the region, and a node
242    /// cut off from the metasrv loses its lease.
243    pub(crate) async fn wait_for_candidate_lease(
244        &self,
245        node_lease: &NodeLease,
246        region_id: RegionId,
247        candidate_lease_id: u64,
248        after: Instant,
249        is_stopped: impl Fn() -> bool,
250    ) -> Result<(), String> {
251        // Registered before the lease is read, so a lease recorded meanwhile wakes the wait.
252        let waiter = self.register(region_id);
253        loop {
254            if is_stopped() {
255                return Err("the region was closed".to_string());
256            }
257            if let Some(result) = self
258                .get(region_id)
259                .and_then(|lease| lease.of_candidate_after(candidate_lease_id, after))
260            {
261                return result;
262            }
263            let (now, deadline) = (node_lease.now(), node_lease.deadline.get());
264            if now >= deadline {
265                return Err("the lease of this node expired".to_string());
266            }
267            tokio::select! {
268                _ = waiter.notify.notified() => {}
269                _ = tokio::time::sleep(Duration::from_nanos(deadline - now)) => {}
270            }
271        }
272    }
273}
274
275impl ObjectStoreWalIoPermit for NodeLease {
276    fn allows_object_store_io(&self) -> bool {
277        !self.is_enabled() || self.now() < self.deadline.get()
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use std::time::Duration;
284
285    use super::*;
286
287    /// Waits until a wait for a candidate lease of `region_id` registered its waiter, so a
288    /// lease recorded or removed afterwards must wake it.
289    async fn wait_until_waiting(leases: &GrantedLeases, region_id: RegionId) {
290        tokio::time::timeout(Duration::from_secs(10), async {
291            while !leases.is_waiting(region_id) {
292                tokio::task::yield_now().await;
293            }
294        })
295        .await
296        .unwrap();
297    }
298
299    #[test]
300    fn test_object_store_permission_follows_node_lease() {
301        let lease = NodeLease::default();
302        assert!(lease.allows_object_store_io());
303        lease.enable();
304        assert!(!lease.allows_object_store_io());
305        let deadline = Instant::now() + Duration::from_secs(10);
306        lease.renew(deadline);
307        lease.freeze_clock(deadline - Duration::from_secs(1));
308        assert!(lease.allows_object_store_io());
309        lease.freeze_clock(deadline);
310        assert!(!lease.allows_object_store_io());
311        lease.renew(deadline + Duration::from_secs(1));
312        assert!(lease.allows_object_store_io());
313        lease.renew(deadline - Duration::from_secs(1));
314        assert!(lease.allows_object_store_io());
315    }
316
317    #[test]
318    fn test_record_checks_region_under_removal_lock() {
319        let leases = GrantedLeases::default();
320        let region_id = RegionId::new(1, 1);
321        leases.record(region_id, Instant::now(), Some(1), || {
322            // A concurrent `remove` waits until the record is done.
323            assert!(leases.0.try_lock().is_err());
324            true
325        });
326        assert_eq!(leases.get(region_id).unwrap().candidate_lease_id, Some(1));
327
328        leases.remove(region_id);
329        leases.record(region_id, Instant::now(), Some(2), || false);
330        assert_eq!(leases.get(region_id), None);
331    }
332
333    /// A node lease that lasts, on a frozen clock, and the instant the wait counts from.
334    fn lasting_node_lease() -> (NodeLease, Instant) {
335        let lease = NodeLease::default();
336        lease.enable();
337        let now = Instant::now();
338        lease.renew(now + Duration::from_secs(60));
339        lease.freeze_clock(now);
340        (lease, now)
341    }
342
343    #[tokio::test]
344    async fn test_candidate_lease_wait_takes_only_a_later_lease() {
345        let (node_lease, after) = lasting_node_lease();
346        let leases = Arc::new(GrantedLeases::default());
347        let region_id = RegionId::new(1, 1);
348        // A lease of a heartbeat sent before the wait began does not count.
349        leases.record(region_id, after, Some(7), || true);
350        let wait = {
351            let leases = leases.clone();
352            tokio::spawn(async move {
353                leases
354                    .wait_for_candidate_lease(&node_lease, region_id, 7, after, || false)
355                    .await
356            })
357        };
358        wait_until_waiting(&leases, region_id).await;
359        assert!(!wait.is_finished());
360
361        leases.record(region_id, after + Duration::from_millis(1), Some(7), || {
362            true
363        });
364        tokio::time::timeout(Duration::from_secs(10), wait)
365            .await
366            .unwrap()
367            .unwrap()
368            .unwrap();
369        // The waiter is gone once the wait ends.
370        assert!(leases.0.lock().unwrap().waiters.is_empty());
371    }
372
373    #[tokio::test]
374    async fn test_candidate_lease_wait_fails_on_another_candidate() {
375        let (node_lease, after) = lasting_node_lease();
376        let leases = GrantedLeases::default();
377        let region_id = RegionId::new(1, 1);
378        let later = after + Duration::from_millis(1);
379        for candidate_lease_id in [None, Some(8)] {
380            leases.record(region_id, later, candidate_lease_id, || true);
381            let reason = leases
382                .wait_for_candidate_lease(&node_lease, region_id, 7, after, || false)
383                .await
384                .unwrap_err();
385            assert!(reason.contains("candidate lease id"), "{reason}");
386            leases.remove(region_id);
387        }
388    }
389
390    #[tokio::test]
391    async fn test_candidate_lease_wait_ends_when_region_is_removed() {
392        let (node_lease, after) = lasting_node_lease();
393        let leases = Arc::new(GrantedLeases::default());
394        let region_id = RegionId::new(1, 1);
395        let stopped = Arc::new(AtomicBool::new(false));
396        let wait = {
397            let (leases, stopped) = (leases.clone(), stopped.clone());
398            tokio::spawn(async move {
399                leases
400                    .wait_for_candidate_lease(&node_lease, region_id, 7, after, || {
401                        stopped.load(Ordering::Relaxed)
402                    })
403                    .await
404            })
405        };
406        wait_until_waiting(&leases, region_id).await;
407        assert!(!wait.is_finished());
408
409        // A close stops the region, then removes it.
410        stopped.store(true, Ordering::Relaxed);
411        leases.remove(region_id);
412        let reason = tokio::time::timeout(Duration::from_secs(10), wait)
413            .await
414            .unwrap()
415            .unwrap()
416            .unwrap_err();
417        assert!(reason.contains("closed"), "{reason}");
418    }
419
420    #[tokio::test]
421    async fn test_candidate_lease_wait_fails_without_node_lease() {
422        let (node_lease, after) = lasting_node_lease();
423        node_lease.freeze_clock(after + Duration::from_secs(60));
424        let reason = GrantedLeases::default()
425            .wait_for_candidate_lease(&node_lease, RegionId::new(1, 1), 7, after, || false)
426            .await
427            .unwrap_err();
428        assert!(reason.contains("expired"), "{reason}");
429    }
430}