Skip to main content

mito2/manifest/
checkpointer.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::fmt::Debug;
16use std::sync::Arc;
17use std::sync::atomic::{AtomicU64, Ordering};
18
19use common_runtime::JoinHandle;
20use common_telemetry::{error, info, warn};
21use store_api::storage::RegionId;
22use store_api::{MIN_VERSION, ManifestVersion};
23#[cfg(test)]
24use tokio::sync::Notify;
25use tokio::sync::watch;
26
27use crate::error::Result;
28use crate::manifest::action::{RegionCheckpoint, RegionManifest};
29use crate::manifest::manager::RegionManifestOptions;
30use crate::manifest::storage::ManifestObjectStore;
31use crate::metrics::MANIFEST_OP_ELAPSED;
32
33/// [`Checkpointer`] is responsible for doing checkpoint for a region, in an asynchronous way.
34#[derive(Debug)]
35pub(crate) struct Checkpointer {
36    manifest_options: RegionManifestOptions,
37    inner: Arc<Inner>,
38    checkpoint_task: Option<CheckpointTask>,
39    #[cfg(test)]
40    pending_checkpoint_wait_started: Arc<Notify>,
41}
42
43/// A spawned checkpoint task and the signal that it has ended.
44#[derive(Debug)]
45struct CheckpointTask {
46    handle: JoinHandle<()>,
47    /// Closes when the task ends, so that it can be awaited without borrowing the checkpointer.
48    done: watch::Receiver<()>,
49}
50
51#[derive(Debug)]
52struct Inner {
53    region_id: RegionId,
54    manifest_store: ManifestObjectStore,
55    last_checkpoint_version: AtomicU64,
56}
57
58impl Inner {
59    async fn do_checkpoint(&self, checkpoint: RegionCheckpoint) {
60        let _t = MANIFEST_OP_ELAPSED
61            .with_label_values(&["checkpoint"])
62            .start_timer();
63
64        let region_id = self.region_id();
65        let version = checkpoint.last_version();
66        let checkpoint = match checkpoint.encode() {
67            Ok(checkpoint) => checkpoint,
68            Err(e) => {
69                error!(e; "Failed to encode checkpoint {:?}", checkpoint);
70                return;
71            }
72        };
73        if let Err(e) = self
74            .manifest_store
75            .save_checkpoint(version, &checkpoint)
76            .await
77        {
78            error!(e; "Failed to save checkpoint for region {}", region_id);
79            return;
80        }
81
82        // Advance the in-memory checkpoint version as soon as the checkpoint file
83        // is durable. If the subsequent delta cleanup fails, the on-disk state is
84        // still consistent (the `_last_checkpoint` metadata points at the new
85        // checkpoint) and `maybe_do_checkpoint` must not re-checkpoint the same
86        // range.
87        self.last_checkpoint_version
88            .store(version, Ordering::Relaxed);
89
90        // Logical retention changes when the checkpoint is published, even if cleanup fails.
91        self.manifest_store.retain_manifest_size_after(version);
92
93        if let Err(e) = self.manifest_store.delete_until(version, true).await {
94            warn!(e; "Failed to delete manifest actions until version {} for region {}, leftover files will be ignored on recovery", version, region_id);
95        }
96
97        info!(
98            "Checkpoint for region {} success, version: {}",
99            region_id, version
100        );
101    }
102
103    fn region_id(&self) -> RegionId {
104        self.region_id
105    }
106}
107
108impl Checkpointer {
109    pub(crate) fn new(
110        region_id: RegionId,
111        manifest_options: RegionManifestOptions,
112        manifest_store: ManifestObjectStore,
113        last_checkpoint_version: ManifestVersion,
114    ) -> Self {
115        Self {
116            manifest_options,
117            inner: Arc::new(Inner {
118                region_id,
119                manifest_store,
120                last_checkpoint_version: AtomicU64::new(last_checkpoint_version),
121            }),
122            checkpoint_task: None,
123            #[cfg(test)]
124            pending_checkpoint_wait_started: Arc::new(Notify::new()),
125        }
126    }
127
128    pub(crate) fn last_checkpoint_version(&self) -> ManifestVersion {
129        self.inner.last_checkpoint_version.load(Ordering::Relaxed)
130    }
131
132    /// Update the `removed_files` field in the manifest by the options in `manifest_options`.
133    /// This should be called before maybe do checkpoint to update the manifest.
134    pub(crate) fn update_manifest_removed_files(
135        &self,
136        mut manifest: RegionManifest,
137    ) -> Result<RegionManifest> {
138        let opt = &self.manifest_options.remove_file_options;
139
140        manifest.removed_files.evict_old_removed_files(opt)?;
141
142        // TODO(discord9): consider also check object store to clear removed files that are already deleted? How costly it is?
143
144        Ok(manifest)
145    }
146
147    /// Check if it's needed to do checkpoint for the region by the checkpoint distance.
148    /// If needed, and there's no currently running checkpoint task, it will start a new checkpoint
149    /// task running in the background.
150    pub(crate) async fn maybe_do_checkpoint(&mut self, manifest: &RegionManifest) {
151        if self
152            .checkpoint_task
153            .as_ref()
154            .is_some_and(|task| !task.handle.is_finished())
155        {
156            return;
157        }
158
159        // Reap a completed task before checking whether to start the next one.
160        // This keeps the handle as the single source of truth for task state.
161        self.wait_for_pending_checkpoint().await;
162
163        if self.manifest_options.checkpoint_distance == 0 {
164            return;
165        }
166
167        let last_checkpoint_version = self.last_checkpoint_version();
168        if manifest.manifest_version - last_checkpoint_version
169            < self.manifest_options.checkpoint_distance
170        {
171            return;
172        }
173
174        let start_version = if last_checkpoint_version == 0 {
175            // Checkpoint version can't be zero by implementation.
176            // So last checkpoint version is zero means no last checkpoint.
177            MIN_VERSION
178        } else {
179            last_checkpoint_version + 1
180        };
181        let end_version = manifest.manifest_version;
182        info!(
183            "Start doing checkpoint for region {}, compacted version: [{}, {}]",
184            self.inner.region_id(),
185            start_version,
186            end_version,
187        );
188
189        let checkpoint = RegionCheckpoint {
190            last_version: end_version,
191            compacted_actions: (end_version - start_version + 1) as usize,
192            checkpoint: Some(manifest.clone()),
193        };
194        self.do_checkpoint(checkpoint);
195    }
196
197    fn do_checkpoint(&mut self, checkpoint: RegionCheckpoint) {
198        let inner = self.inner.clone();
199        let (done_sender, done) = watch::channel(());
200        let handle = common_runtime::spawn_global(async move {
201            // The sender is dropped however the task ends, which closes the channel.
202            let _done_sender = done_sender;
203            inner.do_checkpoint(checkpoint).await;
204        });
205        self.checkpoint_task = Some(CheckpointTask { handle, done });
206    }
207
208    /// Returns a future that resolves once the checkpoint task running now has ended.
209    ///
210    /// Unlike [Self::wait_for_pending_checkpoint], which borrows the checkpointer mutably and reaps
211    /// the task handle, this does neither, so the caller can await the future without holding the
212    /// manifest lock.
213    pub(crate) fn pending_checkpoint_completion(&self) -> impl Future<Output = ()> + Send + use<> {
214        let done = self.checkpoint_task.as_ref().map(|task| task.done.clone());
215        let region_id = self.inner.region_id();
216        #[cfg(test)]
217        let wait_started = self.pending_checkpoint_wait_started.clone();
218        async move {
219            // The channel is closed once the task has ended.
220            let Some(mut done) = done.filter(|receiver| receiver.has_changed().is_ok()) else {
221                return;
222            };
223            #[cfg(test)]
224            wait_started.notify_one();
225            info!("Waiting for the pending checkpoint of region {}", region_id);
226            // Nothing is ever sent, so this returns once the task drops the sender.
227            let _ = done.changed().await;
228        }
229    }
230
231    /// Waits for the current checkpoint task without removing its handle first.
232    ///
233    /// Keeping the handle in `self` while awaiting is important. If the caller is
234    /// cancelled, another lifecycle transition can still wait for the same task.
235    pub(crate) async fn wait_for_pending_checkpoint(&mut self) {
236        let Some(task) = self.checkpoint_task.as_mut() else {
237            return;
238        };
239
240        #[cfg(test)]
241        self.pending_checkpoint_wait_started.notify_one();
242
243        let result = (&mut task.handle).await;
244        // There is no cancellation point between observing completion and
245        // clearing the handle.
246        self.checkpoint_task = None;
247
248        if let Err(e) = result {
249            warn!(e; "Failed to join checkpoint task for region {}", self.inner.region_id());
250        }
251    }
252
253    #[cfg(test)]
254    pub(crate) fn is_doing_checkpoint(&self) -> bool {
255        self.checkpoint_task
256            .as_ref()
257            .is_some_and(|task| !task.handle.is_finished())
258    }
259
260    #[cfg(test)]
261    pub(crate) fn abort_checkpoint_task(&self) {
262        self.checkpoint_task
263            .as_ref()
264            .expect("checkpoint task must exist")
265            .handle
266            .abort();
267    }
268
269    #[cfg(test)]
270    pub(crate) fn pending_checkpoint_wait_started(&self) -> Arc<Notify> {
271        self.pending_checkpoint_wait_started.clone()
272    }
273}