Skip to main content

risingwave_meta/backup_restore/
backup_manager.rs

1// Copyright 2022 RisingWave Labs
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::HashSet;
16use std::sync::Arc;
17use std::time::Instant;
18
19use arc_swap::ArcSwap;
20use risingwave_backup::error::BackupError;
21use risingwave_backup::storage::{MetaSnapshotStorage, ObjectStoreMetaSnapshotStorage};
22use risingwave_backup::{MetaBackupJobId, MetaSnapshotId, MetaSnapshotManifest};
23use risingwave_common::bail;
24use risingwave_common::config::ObjectStoreConfig;
25use risingwave_common::system_param::reader::SystemParamsRead;
26use risingwave_hummock_sdk::HummockRawObjectId;
27use risingwave_object_store::object::build_remote_object_store;
28use risingwave_object_store::object::object_metrics::ObjectStoreMetrics;
29use risingwave_pb::backup_service::{BackupJobStatus, MetaBackupManifestId};
30use risingwave_pb::meta::subscribe_response::{Info, Operation};
31use thiserror_ext::AsReport;
32use tokio::task::JoinHandle;
33
34use crate::MetaResult;
35use crate::backup_restore::meta_snapshot_builder;
36use crate::backup_restore::metrics::BackupManagerMetrics;
37use crate::hummock::sequence::next_meta_backup_id;
38use crate::hummock::{HummockManagerRef, HummockVersionSafePoint};
39use crate::manager::{LocalNotification, MetaSrvEnv};
40use crate::rpc::metrics::MetaMetrics;
41
42pub enum BackupJobResult {
43    Succeeded,
44    Failed(BackupError),
45}
46
47/// `BackupJobHandle` tracks running job.
48struct BackupJobHandle {
49    job_id: u64,
50    #[expect(dead_code)]
51    hummock_version_safe_point: HummockVersionSafePoint,
52    start_time: Instant,
53}
54
55impl BackupJobHandle {
56    pub fn new(job_id: u64, hummock_version_safe_point: HummockVersionSafePoint) -> Self {
57        Self {
58            job_id,
59            hummock_version_safe_point,
60            start_time: Instant::now(),
61        }
62    }
63}
64
65pub type BackupManagerRef = Arc<BackupManager>;
66/// (url, dir)
67type StoreConfig = (String, String);
68
69/// `BackupManager` manages lifecycle of all existent backups and the running backup job.
70pub struct BackupManager {
71    env: MetaSrvEnv,
72    hummock_manager: HummockManagerRef,
73    backup_store: ArcSwap<(ObjectStoreMetaSnapshotStorage, StoreConfig)>,
74    /// Tracks the running backup job. Concurrent jobs is not supported.
75    running_job_handle: tokio::sync::Mutex<Option<BackupJobHandle>>,
76    metrics: BackupManagerMetrics,
77    meta_metrics: Arc<MetaMetrics>,
78    /// (job id, status, message)
79    latest_job_info: ArcSwap<(MetaBackupJobId, BackupJobStatus, String)>,
80    #[cfg(test)]
81    pub(crate) snapshot_captured: tokio::sync::Mutex<
82        Option<(
83            tokio::sync::oneshot::Sender<()>,
84            tokio::sync::oneshot::Receiver<()>,
85        )>,
86    >,
87}
88
89impl BackupManager {
90    pub async fn new(
91        env: MetaSrvEnv,
92        hummock_manager: HummockManagerRef,
93        metrics: Arc<MetaMetrics>,
94        store_url: &str,
95        store_dir: &str,
96    ) -> MetaResult<Arc<Self>> {
97        let store_config = (store_url.to_owned(), store_dir.to_owned());
98        let store = create_snapshot_store(
99            &store_config,
100            metrics.object_store_metric.clone(),
101            &env.opts.object_store_config,
102        )
103        .await?;
104        tracing::info!(
105            "backup manager initialized: url={}, dir={}",
106            store_config.0,
107            store_config.1
108        );
109        let instance = Arc::new(Self::with_store(
110            env.clone(),
111            hummock_manager,
112            metrics,
113            (store, store_config),
114        ));
115        let (local_notification_tx, mut local_notification_rx) =
116            tokio::sync::mpsc::unbounded_channel();
117        env.notification_manager()
118            .insert_local_sender(local_notification_tx);
119        let this = instance.clone();
120        tokio::spawn(async move {
121            loop {
122                match local_notification_rx.recv().await {
123                    Some(notification) => {
124                        if let LocalNotification::SystemParamsChange(p) = notification {
125                            let new_config = (
126                                p.backup_storage_url().to_owned(),
127                                p.backup_storage_directory().to_owned(),
128                            );
129                            this.handle_new_config(new_config).await;
130                        }
131                    }
132                    None => {
133                        return;
134                    }
135                }
136            }
137        });
138        Ok(instance)
139    }
140
141    async fn handle_new_config(&self, new_config: StoreConfig) {
142        if self.backup_store.load().1 == new_config {
143            return;
144        }
145        if let Err(e) = self.set_store(new_config.clone()).await {
146            // Retry is driven by periodic system params notification.
147            tracing::warn!(
148                url = &new_config.0,
149                dir = &new_config.1,
150                error = %e.as_report(),
151                "failed to apply new backup config",
152            );
153        }
154    }
155
156    fn with_store(
157        env: MetaSrvEnv,
158        hummock_manager: HummockManagerRef,
159        meta_metrics: Arc<MetaMetrics>,
160        backup_store: (ObjectStoreMetaSnapshotStorage, StoreConfig),
161    ) -> Self {
162        Self {
163            env,
164            hummock_manager,
165            backup_store: ArcSwap::from_pointee(backup_store),
166            running_job_handle: tokio::sync::Mutex::new(None),
167            metrics: BackupManagerMetrics::default(),
168            meta_metrics,
169            latest_job_info: ArcSwap::from_pointee((0, BackupJobStatus::NotFound, "".into())),
170            #[cfg(test)]
171            snapshot_captured: Default::default(),
172        }
173    }
174
175    pub async fn set_store(&self, config: StoreConfig) -> MetaResult<()> {
176        let new_store = create_snapshot_store(
177            &config,
178            self.meta_metrics.object_store_metric.clone(),
179            &self.env.opts.object_store_config,
180        )
181        .await?;
182        tracing::info!(
183            "new backup config is applied: url={}, dir={}",
184            config.0,
185            config.1
186        );
187        self.backup_store.store(Arc::new((new_store, config)));
188        Ok(())
189    }
190
191    #[cfg(test)]
192    pub async fn for_test(env: MetaSrvEnv, hummock_manager: HummockManagerRef) -> Self {
193        Self::with_store(
194            env,
195            hummock_manager,
196            Arc::new(MetaMetrics::default()),
197            (
198                risingwave_backup::storage::unused().await,
199                StoreConfig::default(),
200            ),
201        )
202    }
203
204    /// Starts a backup job in background. It's non-blocking.
205    /// Returns job id.
206    pub async fn start_backup_job(
207        self: &Arc<Self>,
208        remarks: Option<String>,
209    ) -> MetaResult<MetaBackupJobId> {
210        let mut guard = self.running_job_handle.lock().await;
211        if let Some(job) = (*guard).as_ref() {
212            bail!(format!(
213                "concurrent backup job is not supported: existent job {}",
214                job.job_id
215            ));
216        }
217        // The reasons to limit number of meta snapshot are:
218        // 1. limit size of `MetaSnapshotManifest`, which is kept in memory by
219        // `ObjectStoreMetaSnapshotStorage`.
220        // 2. limit number of pinned SSTs returned by
221        // `list_pinned_ssts`, which subsequently is used by GC.
222        const MAX_META_SNAPSHOT_NUM: usize = 100;
223        let current_number = self
224            .backup_store
225            .load()
226            .0
227            .manifest()
228            .await
229            .snapshot_metadata
230            .len();
231        if current_number > MAX_META_SNAPSHOT_NUM {
232            bail!(format!(
233                "too many existent meta snapshots, expect at most {}",
234                MAX_META_SNAPSHOT_NUM
235            ))
236        }
237
238        let job_id = next_meta_backup_id(&self.env).await?;
239        self.latest_job_info
240            .store(Arc::new((job_id, BackupJobStatus::Running, "".into())));
241        let hummock_version_safe_point = self.hummock_manager.register_safe_point().await;
242        // Ideally `BackupWorker` and its r/w IO can be made external to meta node.
243        // The justification of keeping `BackupWorker` in meta node are:
244        // - It makes meta node the only writer of backup storage, which eases implementation.
245        // - It's likely meta store is deployed in the same node with meta node.
246        // - IO volume of metadata snapshot is not expected to be large.
247        // - Backup job is not expected to be frequent.
248        BackupWorker::new(self.clone()).start(job_id, remarks);
249        let job_handle = BackupJobHandle::new(job_id, hummock_version_safe_point);
250        *guard = Some(job_handle);
251        self.metrics.job_count.inc();
252        Ok(job_id)
253    }
254
255    pub fn get_backup_job_status(&self, job_id: MetaBackupJobId) -> (BackupJobStatus, String) {
256        let last = self.latest_job_info.load();
257        if last.0 == job_id {
258            return (last.1, last.2.clone());
259        }
260        (BackupJobStatus::NotFound, "".into())
261    }
262
263    async fn finish_backup_job(&self, job_id: MetaBackupJobId, job_result: BackupJobResult) {
264        // `job_handle` holds `hummock_version_safe_point` until the job is completed.
265        let job_handle = self
266            .take_job_handle_by_job_id(job_id)
267            .await
268            .expect("job id should match");
269        let job_latency = job_handle.start_time.elapsed().as_secs_f64();
270        match job_result {
271            BackupJobResult::Succeeded => {
272                self.metrics.job_latency_success.observe(job_latency);
273                tracing::info!("succeeded backup job {}", job_id);
274                self.env.notification_manager().notify_hummock(
275                    Operation::Update,
276                    Info::MetaBackupManifestId(MetaBackupManifestId {
277                        id: self.backup_store.load().0.manifest().await.manifest_id,
278                    }),
279                );
280                self.latest_job_info.store(Arc::new((
281                    job_id,
282                    BackupJobStatus::Succeeded,
283                    "".into(),
284                )));
285            }
286            BackupJobResult::Failed(e) => {
287                self.metrics.job_latency_failure.observe(job_latency);
288                let message = format!("failed backup job {}: {}", job_id, e.as_report());
289                tracing::warn!(message);
290                self.latest_job_info
291                    .store(Arc::new((job_id, BackupJobStatus::Failed, message)));
292            }
293        }
294    }
295
296    async fn take_job_handle_by_job_id(&self, job_id: u64) -> Option<BackupJobHandle> {
297        let mut guard = self.running_job_handle.lock().await;
298        match (*guard).as_ref() {
299            None => {
300                return None;
301            }
302            Some(job_handle) => {
303                if job_handle.job_id != job_id {
304                    return None;
305                }
306            }
307        }
308        guard.take()
309    }
310
311    /// Deletes existent backups from backup storage.
312    pub async fn delete_backups(&self, ids: &[MetaSnapshotId]) -> MetaResult<()> {
313        self.backup_store.load().0.delete(ids).await?;
314        self.env.notification_manager().notify_hummock(
315            Operation::Update,
316            Info::MetaBackupManifestId(MetaBackupManifestId {
317                id: self.backup_store.load().0.manifest().await.manifest_id,
318            }),
319        );
320        Ok(())
321    }
322
323    /// List id of all objects required by backups.
324    pub async fn list_pinned_object_ids(&self) -> HashSet<HummockRawObjectId> {
325        self.backup_store
326            .load()
327            .0
328            .manifest()
329            .await
330            .snapshot_metadata
331            .iter()
332            .flat_map(|s| s.objects.iter().copied())
333            .collect()
334    }
335
336    pub async fn manifest(&self) -> Arc<MetaSnapshotManifest> {
337        self.backup_store.load().0.manifest().await
338    }
339}
340
341/// `BackupWorker` creates a database snapshot.
342struct BackupWorker {
343    backup_manager: BackupManagerRef,
344}
345
346impl BackupWorker {
347    fn new(backup_manager: BackupManagerRef) -> Self {
348        Self { backup_manager }
349    }
350
351    fn start(self, job_id: u64, remarks: Option<String>) -> JoinHandle<()> {
352        let backup_manager_clone = self.backup_manager.clone();
353        let job = async move {
354            let hummock_manager = backup_manager_clone.hummock_manager.clone();
355            let hummock_version_builder = async move {
356                hummock_manager
357                    .on_current_version(|version| version.clone())
358                    .await
359            };
360            let meta_store = backup_manager_clone.env.meta_store();
361            let mut snapshot_builder =
362                meta_snapshot_builder::MetaSnapshotV2Builder::new(meta_store);
363            // Reuse job id as snapshot id.
364            snapshot_builder
365                .build(job_id, hummock_version_builder)
366                .await?;
367            let snapshot = snapshot_builder.finish()?;
368            #[cfg(test)]
369            {
370                let gate = backup_manager_clone.snapshot_captured.lock().await.take();
371                if let Some((captured, publish)) = gate {
372                    captured.send(()).unwrap();
373                    publish.await.unwrap();
374                }
375            }
376            backup_manager_clone
377                .backup_store
378                .load()
379                .0
380                .create(&snapshot, remarks)
381                .await?;
382            Ok(BackupJobResult::Succeeded)
383        };
384        tokio::spawn(async move {
385            let job_result = job.await.unwrap_or_else(BackupJobResult::Failed);
386            self.backup_manager
387                .finish_backup_job(job_id, job_result)
388                .await;
389        })
390    }
391}
392
393async fn create_snapshot_store(
394    config: &StoreConfig,
395    metric: Arc<ObjectStoreMetrics>,
396    object_store_config: &ObjectStoreConfig,
397) -> MetaResult<ObjectStoreMetaSnapshotStorage> {
398    let object_store = Arc::new(
399        build_remote_object_store(
400            &config.0,
401            metric,
402            "Meta Backup",
403            Arc::new(object_store_config.clone()),
404        )
405        .await,
406    );
407    let store = ObjectStoreMetaSnapshotStorage::new(&config.1, object_store).await?;
408    Ok(store)
409}