Skip to main content

mito2/worker/
handle_drop.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
15//! Handling drop request.
16
17use std::time::Duration;
18
19use bytes::Bytes;
20use common_telemetry::{error, info, warn};
21use futures::TryStreamExt;
22use object_store::util::join_path;
23use object_store::{EntryMode, ObjectStore};
24use snafu::ResultExt;
25use store_api::logstore::LogStore;
26use store_api::metadata::RegionMetadataRef;
27use store_api::region_request::{AffectedRows, PathType, RegionDropRequest};
28use store_api::storage::RegionId;
29use tokio::time::sleep;
30
31use crate::cache::CacheManagerRef;
32use crate::engine::region_hook::RegionHookRef;
33use crate::error::{OpenDalSnafu, Result};
34use crate::region::{MitoRegionRef, RegionLeaderState, RegionMapRef};
35use crate::request::{DdlRequest, OptionOutputTx};
36use crate::sst::index::intermediate::IntermediateManager;
37use crate::worker::{DROPPING_MARKER_FILE, RegionWorkerLoop};
38
39const GC_TASK_INTERVAL_SEC: u64 = 5 * 60; // 5 minutes
40const MAX_RETRY_TIMES: u64 = 12; // 1 hours (5m * 12)
41
42impl<S> RegionWorkerLoop<S>
43where
44    S: LogStore,
45{
46    pub(crate) async fn handle_drop_request(
47        &mut self,
48        region_id: RegionId,
49        req: RegionDropRequest,
50        sender: OptionOutputTx,
51    ) {
52        let region = match self.regions.writable_region(region_id) {
53            Ok(region) => region,
54            Err(e) => {
55                sender.send(Err(e));
56                return;
57            }
58        };
59
60        let (sender, req) = match self.flush_scheduler.try_cancel_and_add_ddl(
61            region_id,
62            sender,
63            req,
64            DdlRequest::Drop,
65        ) {
66            Ok(()) => {
67                self.listener.on_flush_cancel_requested(region_id);
68                return;
69            }
70            Err(request) => request,
71        };
72
73        let result = self.drop_region(region, req.partial_drop).await;
74        sender.send(result);
75    }
76
77    async fn drop_region(
78        &mut self,
79        region: MitoRegionRef,
80        partial_drop: bool,
81    ) -> Result<AffectedRows> {
82        let region_id = region.region_id;
83
84        info!("Try to drop region: {}, worker: {}", region_id, self.id);
85
86        let is_staging = region.is_staging();
87        let expect_state = if is_staging {
88            RegionLeaderState::Staging
89        } else {
90            RegionLeaderState::Writable
91        };
92        // Marks the region as dropping.
93        region.set_dropping(expect_state)?;
94        // Writes dropping marker
95        // We rarely drop a region so we still operate in the worker loop.
96        let region_dir = region.access_layer.build_region_dir(region_id);
97        let path_type = region.access_layer.path_type();
98        let table_dir = region.access_layer.table_dir().to_string();
99        let marker_path = join_path(&region_dir, DROPPING_MARKER_FILE);
100        region
101            .access_layer
102            .object_store()
103            .write(&marker_path, Bytes::new())
104            .await
105            .context(OpenDalSnafu)
106            .inspect_err(|e| {
107                error!(e; "Failed to write the drop marker file for region {}", region_id);
108
109                // Sets the state back to writable. It's possible that the marker file has been written.
110                // We set the state back to writable so we can retry the drop operation.
111                region.switch_state_to_writable(RegionLeaderState::Dropping);
112            })?;
113
114        region.stop().await;
115        // Removes this region from region map to prevent other requests from accessing this region
116        self.regions.remove_region(region_id);
117        self.granted_leases.remove(region_id);
118        self.deferred_lease_work.remove(&region_id);
119        region.deactivate_region_manifest_size_metric();
120        self.cancel_tail_replay(region_id);
121        self.dropping_regions.insert_region(region.clone());
122        // The region is no longer served once it leaves the map, so unregister its
123        // runtime state before the fallible WAL cleanup below. Otherwise a WAL
124        // failure would leak the resident compaction/flush/index entries that only
125        // this cleanup and close/drop remove.
126        self.cleanup_dropped_region_runtime_state(region_id).await;
127
128        // Deletes region data in WAL, and releases it so that this outlives a restart, which
129        // never opens the region again. A failure of the object store WAL does not fail the
130        // drop: the region has left the map, a drop request for it is not sent again, and a
131        // caller that drops several regions on one store, such as the metric engine, would
132        // leave the others undone, for instance once the release of one poisoned the store.
133        // The store keeps a failed release and writes it with its next object unless it is
134        // stopped or poisoned.
135        if let Err(e) = self
136            .wal
137            .obsolete(
138                region_id,
139                region.version_control.current().last_entry_id,
140                &region.provider,
141            )
142            .await
143        {
144            if region.provider.as_object_store_provider().is_none() {
145                return Err(e);
146            }
147            error!(e; "Failed to obsolete the WAL of dropped region {}", region_id);
148        }
149        if let Err(e) = self.wal.release_region(region_id, &region.provider).await {
150            error!(e; "Failed to release the WAL of dropped region {}", region_id);
151        }
152
153        // Marks region version as dropped
154        region.version_control.mark_dropped();
155        info!(
156            "Region {} is dropped logically, but some files are not deleted yet",
157            region_id
158        );
159
160        self.region_count.dec();
161
162        // Notify registered hooks that the region has been logically dropped, and
163        // prepare a payload for the background GC task to fire the terminal
164        // `on_region_files_removed`. When no hook is registered this allocates
165        // nothing — no metadata snapshot is taken and no payload is built.
166        let hook_payload = match region.manifest_ctx.hook() {
167            Some(hook) => {
168                let region_metadata = region.metadata();
169                hook.on_region_dropped(region_id, &region_metadata).await;
170                Some(DropHookPayload {
171                    hook,
172                    metadata: region_metadata,
173                })
174            }
175            None => None,
176        };
177
178        let object_store = region.access_layer.object_store().clone();
179        let dropping_regions = self.dropping_regions.clone();
180        let listener = self.listener.clone();
181        let intm_manager = self.intermediate_manager.clone();
182        let cache_manager = self.cache_manager.clone();
183        let gc_enabled = self.file_ref_manager.is_gc_enabled();
184
185        common_runtime::spawn_global(async move {
186            let removed = if gc_enabled {
187                later_drop_task_with_global_gc(
188                    region_id,
189                    region_dir.clone(),
190                    path_type,
191                    object_store,
192                    dropping_regions,
193                    partial_drop,
194                    hook_payload.as_ref(),
195                )
196                .await
197            } else {
198                let gc_duration = listener
199                    .on_later_drop_begin(region_id)
200                    .unwrap_or(Duration::from_secs(GC_TASK_INTERVAL_SEC));
201
202                later_drop_task_without_global_gc(
203                    region_id,
204                    region_dir.clone(),
205                    object_store,
206                    dropping_regions,
207                    gc_duration,
208                    hook_payload.as_ref(),
209                )
210                .await
211            };
212
213            cleanup_region_file_artifacts(region_id, &table_dir, &intm_manager, &cache_manager)
214                .await;
215
216            listener.on_later_drop_end(region_id, removed);
217        });
218
219        Ok(0)
220    }
221
222    /// Cleans runtime state for a region that is no longer available to serve requests.
223    pub(crate) async fn cleanup_dropped_region_runtime_state(&mut self, region_id: RegionId) {
224        // A successful flush may hand off DROP before queued ALTERs and edits resume.
225        // Reject their waiters here because the removed region has no next turn.
226        self.reject_region_requests_as_not_found(region_id);
227        // Notifies flush scheduler.
228        self.flush_scheduler.on_region_dropped(region_id);
229        // Notifies compaction scheduler.
230        self.compaction_scheduler.on_region_dropped(region_id);
231        // Notifies index build scheduler.
232        self.index_build_scheduler
233            .on_region_dropped(region_id)
234            .await;
235    }
236}
237
238/// Cleans files and caches that are produced at runtime but are not part of the
239/// primary region directory deletion.
240pub(crate) async fn cleanup_region_file_artifacts(
241    region_id: RegionId,
242    table_dir: &str,
243    intermediate_manager: &IntermediateManager,
244    cache_manager: &CacheManagerRef,
245) {
246    if let Err(err) = intermediate_manager.prune_region_dir(&region_id).await {
247        warn!(err; "Failed to prune intermediate region directory, region_id: {}", region_id);
248    }
249
250    if let Some(write_cache) = cache_manager.write_cache()
251        && let Some(manifest_cache) = write_cache.manifest_cache()
252    {
253        manifest_cache.clean_manifests(table_dir).await;
254    }
255}
256
257/// Removes a region directory for full-drop style cleanup.
258///
259/// Full drop and purge/offline cleanup force physical deletion. Only partial
260/// drop may leave data files for global GC.
261pub(crate) async fn remove_region_dir_for_full_drop(
262    region_path: &str,
263    object_store: &ObjectStore,
264) -> Result<()> {
265    remove_region_dir_once(region_path, object_store, true).await?;
266    Ok(())
267}
268
269/// Carries the region hook and region metadata into the background GC task so
270/// it can fire [`RegionHook::on_region_files_removed`] once the dropped region's
271/// directory is physically deleted.
272///
273/// Only constructed when a hook is registered; the task receives it as
274/// `Option<&DropHookPayload>` so the no-hook path allocates nothing.
275///
276/// [`RegionHook::on_region_files_removed`]: crate::engine::region_hook::RegionHook::on_region_files_removed
277struct DropHookPayload {
278    hook: RegionHookRef,
279    metadata: RegionMetadataRef,
280}
281
282/// Background GC task to remove the entire region path once one of the following
283/// conditions is true:
284/// - It finds there is no parquet file left.
285/// - After `gc_duration`.
286///
287/// Returns whether the path is removed.
288///
289/// This task will retry on failure and keep running until finished. Any resource
290/// captured by it will not be released before then. Be sure to only pass weak reference
291/// if something is depended on ref-count mechanism.
292async fn later_drop_task_without_global_gc(
293    region_id: RegionId,
294    region_path: String,
295    object_store: ObjectStore,
296    dropping_regions: RegionMapRef,
297    gc_duration: Duration,
298    hook_payload: Option<&DropHookPayload>,
299) -> bool {
300    remove_region_with_retry(
301        region_id,
302        region_path,
303        object_store,
304        dropping_regions,
305        Some(gc_duration),
306        false,
307        hook_payload,
308    )
309    .await
310}
311
312async fn remove_region_with_retry(
313    region_id: RegionId,
314    region_path: String,
315    object_store: ObjectStore,
316    dropping_regions: std::sync::Arc<crate::region::RegionMap>,
317    gc_duration: Option<Duration>,
318    mut force: bool,
319    hook_payload: Option<&DropHookPayload>,
320) -> bool {
321    for _ in 0..MAX_RETRY_TIMES {
322        let result = remove_region_dir_once(&region_path, &object_store, force).await;
323        match result {
324            Err(err) => {
325                warn!(
326                    "Error occurs during trying to GC region dir {}: {}",
327                    region_path, err
328                );
329            }
330            Ok(true) => {
331                dropping_regions.remove_region(region_id);
332                info!("Region {} is dropped, force: {}", region_path, force);
333                // The region directory has been physically deleted; fire the
334                // terminal file-lifecycle event. The partial-drop/global-GC path
335                // never reaches here (it does not delete the directory itself).
336                if let Some(hook_payload) = hook_payload {
337                    hook_payload
338                        .hook
339                        .on_region_files_removed(region_id, &hook_payload.metadata)
340                        .await;
341                }
342                return true;
343            }
344            Ok(false) => (),
345        }
346        if let Some(duration) = gc_duration {
347            sleep(duration).await;
348        }
349        // Force recycle after gc duration.
350        force = true;
351    }
352
353    warn!(
354        "Failed to GC region dir {} after {} retries, giving up",
355        region_path, MAX_RETRY_TIMES
356    );
357
358    false
359}
360
361async fn later_drop_task_with_global_gc(
362    region_id: RegionId,
363    region_path: String,
364    path_type: PathType,
365    object_store: ObjectStore,
366    dropping_regions: RegionMapRef,
367    partial_drop: bool,
368    hook_payload: Option<&DropHookPayload>,
369) -> bool {
370    // For metadata regions or regions marked for full deletion (such as when dropping a table)
371    // the region directory is forcefully removed immediately.
372    //
373    // TODO(discord9): Evaluate removing files instantly rather than waiting for the GC period.
374    if should_force_remove_region_dir(path_type, partial_drop) {
375        remove_region_with_retry(
376            region_id,
377            region_path,
378            object_store,
379            dropping_regions,
380            None,
381            true,
382            hook_payload,
383        )
384        .await
385    } else {
386        // left for global gc
387        dropping_regions.remove_region(region_id);
388        true
389    }
390}
391
392fn should_force_remove_region_dir(path_type: PathType, partial_drop: bool) -> bool {
393    path_type == PathType::Metadata || !partial_drop
394}
395
396// TODO(ruihang): place the marker in a separate dir
397/// Removes a region directory once no authoritative SST objects remain.
398/// If `force = true`, always removes the dir.
399pub(crate) async fn remove_region_dir_once(
400    region_path: &str,
401    object_store: &ObjectStore,
402    force: bool,
403) -> Result<bool> {
404    // Narthex SSTs have objects below their file-ID directories.
405    let mut has_sst_file = false;
406    // Record non-SST files to remove before the dropping marker.
407    let mut files_to_remove_first = vec![];
408    let mut files = object_store
409        .lister_with(region_path)
410        .recursive(true)
411        .await
412        .context(OpenDalSnafu)?;
413    while let Some(file) = files.try_next().await.context(OpenDalSnafu)? {
414        if !force
415            && (file.path().ends_with(".parquet")
416                || crate::sst::location::parse_narthex_file_id(file.path()).is_some())
417        {
418            // Readers may still pin either narthex samples or series indexes.
419            has_sst_file = true;
420            break;
421        } else if !file.path().ends_with(DROPPING_MARKER_FILE) {
422            let meta = file.metadata();
423            if meta.mode() == EntryMode::FILE {
424                files_to_remove_first.push(file.path().to_string());
425            }
426        }
427    }
428
429    if !has_sst_file {
430        // No authoritative SST objects remain; delete the region path.
431        // first delete all files other than the marker
432        object_store
433            .delete_iter(files_to_remove_first)
434            .await
435            .context(OpenDalSnafu)?;
436        // then remove the marker with this dir
437        object_store
438            .delete_with(region_path)
439            .recursive(true)
440            .await
441            .context(OpenDalSnafu)?;
442        Ok(true)
443    } else {
444        Ok(false)
445    }
446}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451
452    #[tokio::test]
453    async fn test_narthex_objects_prevent_region_directory_removal() {
454        let store = ObjectStore::new(object_store::services::Memory::default()).unwrap();
455        let region = "test/region/";
456        let id = store_api::storage::FileId::random();
457        let marker = format!("{region}{DROPPING_MARKER_FILE}");
458        let samples = format!(
459            "{}part-0.samples",
460            crate::sst::location::narthex_file_dir(region, id)
461        );
462        let series = format!(
463            "{}part-0.series",
464            crate::sst::location::narthex_file_dir(region, id)
465        );
466        store.write(&marker, Bytes::new()).await.unwrap();
467        for path in [&samples, &series] {
468            store
469                .write(path, Bytes::from_static(b"test"))
470                .await
471                .unwrap();
472        }
473        assert!(!remove_region_dir_once(region, &store, false).await.unwrap());
474        store.delete(&samples).await.unwrap();
475        assert!(!remove_region_dir_once(region, &store, false).await.unwrap());
476        assert!(store.exists(&series).await.unwrap());
477        assert!(store.exists(&marker).await.unwrap());
478        store.delete(&series).await.unwrap();
479        assert!(remove_region_dir_once(region, &store, false).await.unwrap());
480        assert!(!store.exists(&marker).await.unwrap());
481    }
482}