LCOV - code coverage report
Current view: top level - pageserver/src/tenant/timeline - delete.rs (source / functions) Coverage Total Hit
Test: 53437f7e869ac68c86c7d3e4c20964c0156f158c.info Lines: 0.0 % 200 0
Test Date: 2024-09-20 16:14:12 Functions: 0.0 % 25 0

            Line data    Source code
       1              : use std::{
       2              :     ops::{Deref, DerefMut},
       3              :     sync::Arc,
       4              : };
       5              : 
       6              : use anyhow::Context;
       7              : use pageserver_api::{models::TimelineState, shard::TenantShardId};
       8              : use tokio::sync::OwnedMutexGuard;
       9              : use tracing::{error, info, instrument, Instrument};
      10              : use utils::{crashsafe, fs_ext, id::TimelineId, pausable_failpoint};
      11              : 
      12              : use crate::{
      13              :     config::PageServerConf,
      14              :     task_mgr::{self, TaskKind},
      15              :     tenant::{
      16              :         metadata::TimelineMetadata,
      17              :         remote_timeline_client::{PersistIndexPartWithDeletedFlagError, RemoteTimelineClient},
      18              :         CreateTimelineCause, DeleteTimelineError, Tenant,
      19              :     },
      20              : };
      21              : 
      22              : use super::{Timeline, TimelineResources};
      23              : 
      24              : /// Mark timeline as deleted in S3 so we won't pick it up next time
      25              : /// during attach or pageserver restart.
      26              : /// See comment in persist_index_part_with_deleted_flag.
      27            0 : async fn set_deleted_in_remote_index(timeline: &Timeline) -> Result<(), DeleteTimelineError> {
      28            0 :     match timeline
      29            0 :         .remote_client
      30            0 :         .persist_index_part_with_deleted_flag()
      31            0 :         .await
      32              :     {
      33              :         // If we (now, or already) marked it successfully as deleted, we can proceed
      34            0 :         Ok(()) | Err(PersistIndexPartWithDeletedFlagError::AlreadyDeleted(_)) => (),
      35              :         // Bail out otherwise
      36              :         //
      37              :         // AlreadyInProgress shouldn't happen, because the 'delete_lock' prevents
      38              :         // two tasks from performing the deletion at the same time. The first task
      39              :         // that starts deletion should run it to completion.
      40            0 :         Err(e @ PersistIndexPartWithDeletedFlagError::AlreadyInProgress(_))
      41            0 :         | Err(e @ PersistIndexPartWithDeletedFlagError::Other(_)) => {
      42            0 :             return Err(DeleteTimelineError::Other(anyhow::anyhow!(e)));
      43              :         }
      44              :     }
      45            0 :     Ok(())
      46            0 : }
      47              : 
      48              : /// Grab the compaction and gc locks, and actually perform the deletion.
      49              : ///
      50              : /// The locks prevent GC or compaction from running at the same time. The background tasks do not
      51              : /// register themselves with the timeline it's operating on, so it might still be running even
      52              : /// though we called `shutdown_tasks`.
      53              : ///
      54              : /// Note that there are still other race conditions between
      55              : /// GC, compaction and timeline deletion. See
      56              : /// <https://github.com/neondatabase/neon/issues/2671>
      57              : ///
      58              : /// No timeout here, GC & Compaction should be responsive to the
      59              : /// `TimelineState::Stopping` change.
      60              : // pub(super): documentation link
      61            0 : pub(super) async fn delete_local_timeline_directory(
      62            0 :     conf: &PageServerConf,
      63            0 :     tenant_shard_id: TenantShardId,
      64            0 :     timeline: &Timeline,
      65            0 : ) -> anyhow::Result<()> {
      66            0 :     // Always ensure the lock order is compaction -> gc.
      67            0 :     let compaction_lock = timeline.compaction_lock.lock();
      68            0 :     let compaction_lock = crate::timed(
      69            0 :         compaction_lock,
      70            0 :         "acquires compaction lock",
      71            0 :         std::time::Duration::from_secs(5),
      72            0 :     )
      73            0 :     .await;
      74              : 
      75            0 :     let gc_lock = timeline.gc_lock.lock();
      76            0 :     let gc_lock = crate::timed(
      77            0 :         gc_lock,
      78            0 :         "acquires gc lock",
      79            0 :         std::time::Duration::from_secs(5),
      80            0 :     )
      81            0 :     .await;
      82              : 
      83              :     // NB: storage_sync upload tasks that reference these layers have been cancelled
      84              :     //     by the caller.
      85              : 
      86            0 :     let local_timeline_directory = conf.timeline_path(&tenant_shard_id, &timeline.timeline_id);
      87            0 : 
      88            0 :     fail::fail_point!("timeline-delete-before-rm", |_| {
      89            0 :         Err(anyhow::anyhow!("failpoint: timeline-delete-before-rm"))?
      90            0 :     });
      91              : 
      92              :     // NB: This need not be atomic because the deleted flag in the IndexPart
      93              :     // will be observed during tenant/timeline load. The deletion will be resumed there.
      94              :     //
      95              :     // Note that here we do not bail out on std::io::ErrorKind::NotFound.
      96              :     // This can happen if we're called a second time, e.g.,
      97              :     // because of a previous failure/cancellation at/after
      98              :     // failpoint timeline-delete-after-rm.
      99              :     //
     100              :     // ErrorKind::NotFound can also happen if we race with tenant detach, because,
     101              :     // no locks are shared.
     102            0 :     tokio::fs::remove_dir_all(local_timeline_directory)
     103            0 :         .await
     104            0 :         .or_else(fs_ext::ignore_not_found)
     105            0 :         .context("remove local timeline directory")?;
     106              : 
     107              :     // Make sure previous deletions are ordered before mark removal.
     108              :     // Otherwise there is no guarantee that they reach the disk before mark deletion.
     109              :     // So its possible for mark to reach disk first and for other deletions
     110              :     // to be reordered later and thus missed if a crash occurs.
     111              :     // Note that we dont need to sync after mark file is removed
     112              :     // because we can tolerate the case when mark file reappears on startup.
     113            0 :     let timeline_path = conf.timelines_path(&tenant_shard_id);
     114            0 :     crashsafe::fsync_async(timeline_path)
     115            0 :         .await
     116            0 :         .context("fsync_pre_mark_remove")?;
     117              : 
     118            0 :     info!("finished deleting layer files, releasing locks");
     119            0 :     drop(gc_lock);
     120            0 :     drop(compaction_lock);
     121            0 : 
     122            0 :     fail::fail_point!("timeline-delete-after-rm", |_| {
     123            0 :         Err(anyhow::anyhow!("failpoint: timeline-delete-after-rm"))?
     124            0 :     });
     125              : 
     126            0 :     Ok(())
     127            0 : }
     128              : 
     129              : /// Removes remote layers and an index file after them.
     130            0 : async fn delete_remote_layers_and_index(timeline: &Timeline) -> anyhow::Result<()> {
     131            0 :     timeline
     132            0 :         .remote_client
     133            0 :         .delete_all()
     134            0 :         .await
     135            0 :         .context("delete_all")
     136            0 : }
     137              : 
     138              : /// It is important that this gets called when DeletionGuard is being held.
     139              : /// For more context see comments in [`DeleteTimelineFlow::prepare`]
     140            0 : async fn remove_timeline_from_tenant(
     141            0 :     tenant: &Tenant,
     142            0 :     timeline: &Timeline,
     143            0 :     _: &DeletionGuard, // using it as a witness
     144            0 : ) -> anyhow::Result<()> {
     145            0 :     // Remove the timeline from the map.
     146            0 :     let mut timelines = tenant.timelines.lock().unwrap();
     147            0 :     let children_exist = timelines
     148            0 :         .iter()
     149            0 :         .any(|(_, entry)| entry.get_ancestor_timeline_id() == Some(timeline.timeline_id));
     150            0 :     // XXX this can happen because `branch_timeline` doesn't check `TimelineState::Stopping`.
     151            0 :     // We already deleted the layer files, so it's probably best to panic.
     152            0 :     // (Ideally, above remove_dir_all is atomic so we don't see this timeline after a restart)
     153            0 :     if children_exist {
     154            0 :         panic!("Timeline grew children while we removed layer files");
     155            0 :     }
     156            0 : 
     157            0 :     timelines
     158            0 :         .remove(&timeline.timeline_id)
     159            0 :         .expect("timeline that we were deleting was concurrently removed from 'timelines' map");
     160            0 : 
     161            0 :     drop(timelines);
     162            0 : 
     163            0 :     Ok(())
     164            0 : }
     165              : 
     166              : /// Orchestrates timeline shut down of all timeline tasks, removes its in-memory structures,
     167              : /// and deletes its data from both disk and s3.
     168              : /// The sequence of steps:
     169              : /// 1. Set deleted_at in remote index part.
     170              : /// 2. Create local mark file.
     171              : /// 3. Delete local files except metadata (it is simpler this way, to be able to reuse timeline initialization code that expects metadata)
     172              : /// 4. Delete remote layers
     173              : /// 5. Delete index part
     174              : /// 6. Delete meta, timeline directory
     175              : /// 7. Delete mark file
     176              : ///
     177              : /// It is resumable from any step in case a crash/restart occurs.
     178              : /// There are two entrypoints to the process:
     179              : /// 1. [`DeleteTimelineFlow::run`] this is the main one called by a management api handler.
     180              : /// 2. [`DeleteTimelineFlow::resume_deletion`] is called during restarts when local metadata is still present
     181              : ///    and we possibly neeed to continue deletion of remote files.
     182              : ///
     183              : /// Note the only other place that messes around timeline delete mark is the logic that scans directory with timelines during tenant load.
     184              : #[derive(Default)]
     185              : pub enum DeleteTimelineFlow {
     186              :     #[default]
     187              :     NotStarted,
     188              :     InProgress,
     189              :     Finished,
     190              : }
     191              : 
     192              : impl DeleteTimelineFlow {
     193              :     // These steps are run in the context of management api request handler.
     194              :     // Long running steps are continued to run in the background.
     195              :     // NB: If this fails half-way through, and is retried, the retry will go through
     196              :     // all the same steps again. Make sure the code here is idempotent, and don't
     197              :     // error out if some of the shutdown tasks have already been completed!
     198            0 :     #[instrument(skip_all)]
     199              :     pub async fn run(
     200              :         tenant: &Arc<Tenant>,
     201              :         timeline_id: TimelineId,
     202              :     ) -> Result<(), DeleteTimelineError> {
     203              :         super::debug_assert_current_span_has_tenant_and_timeline_id();
     204              : 
     205              :         let (timeline, mut guard) = Self::prepare(tenant, timeline_id)?;
     206              : 
     207              :         guard.mark_in_progress()?;
     208              : 
     209              :         // Now that the Timeline is in Stopping state, request all the related tasks to shut down.
     210              :         timeline.shutdown(super::ShutdownMode::Hard).await;
     211              : 
     212              :         tenant.gc_block.before_delete(&timeline);
     213              : 
     214            0 :         fail::fail_point!("timeline-delete-before-index-deleted-at", |_| {
     215            0 :             Err(anyhow::anyhow!(
     216            0 :                 "failpoint: timeline-delete-before-index-deleted-at"
     217            0 :             ))?
     218            0 :         });
     219              : 
     220              :         set_deleted_in_remote_index(&timeline).await?;
     221              : 
     222            0 :         fail::fail_point!("timeline-delete-before-schedule", |_| {
     223            0 :             Err(anyhow::anyhow!(
     224            0 :                 "failpoint: timeline-delete-before-schedule"
     225            0 :             ))?
     226            0 :         });
     227              : 
     228              :         Self::schedule_background(guard, tenant.conf, Arc::clone(tenant), timeline);
     229              : 
     230              :         Ok(())
     231              :     }
     232              : 
     233            0 :     fn mark_in_progress(&mut self) -> anyhow::Result<()> {
     234            0 :         match self {
     235            0 :             Self::Finished => anyhow::bail!("Bug. Is in finished state"),
     236            0 :             Self::InProgress { .. } => { /* We're in a retry */ }
     237            0 :             Self::NotStarted => { /* Fresh start */ }
     238              :         }
     239              : 
     240            0 :         *self = Self::InProgress;
     241            0 : 
     242            0 :         Ok(())
     243            0 :     }
     244              : 
     245              :     /// Shortcut to create Timeline in stopping state and spawn deletion task.
     246            0 :     #[instrument(skip_all, fields(%timeline_id))]
     247              :     pub async fn resume_deletion(
     248              :         tenant: Arc<Tenant>,
     249              :         timeline_id: TimelineId,
     250              :         local_metadata: &TimelineMetadata,
     251              :         remote_client: RemoteTimelineClient,
     252              :     ) -> anyhow::Result<()> {
     253              :         // Note: here we even skip populating layer map. Timeline is essentially uninitialized.
     254              :         // RemoteTimelineClient is the only functioning part.
     255              :         let timeline = tenant
     256              :             .create_timeline_struct(
     257              :                 timeline_id,
     258              :                 local_metadata,
     259              :                 None, // Ancestor is not needed for deletion.
     260              :                 TimelineResources {
     261              :                     remote_client,
     262              :                     timeline_get_throttle: tenant.timeline_get_throttle.clone(),
     263              :                     l0_flush_global_state: tenant.l0_flush_global_state.clone(),
     264              :                 },
     265              :                 // Important. We dont pass ancestor above because it can be missing.
     266              :                 // Thus we need to skip the validation here.
     267              :                 CreateTimelineCause::Delete,
     268              :                 // Aux file policy is not needed for deletion, assuming deletion does not read aux keyspace
     269              :                 None,
     270              :             )
     271              :             .context("create_timeline_struct")?;
     272              : 
     273              :         let mut guard = DeletionGuard(
     274              :             Arc::clone(&timeline.delete_progress)
     275              :                 .try_lock_owned()
     276              :                 .expect("cannot happen because we're the only owner"),
     277              :         );
     278              : 
     279              :         // We meed to do this because when console retries delete request we shouldnt answer with 404
     280              :         // because 404 means successful deletion.
     281              :         {
     282              :             let mut locked = tenant.timelines.lock().unwrap();
     283              :             locked.insert(timeline_id, Arc::clone(&timeline));
     284              :         }
     285              : 
     286              :         guard.mark_in_progress()?;
     287              : 
     288              :         Self::schedule_background(guard, tenant.conf, tenant, timeline);
     289              : 
     290              :         Ok(())
     291              :     }
     292              : 
     293            0 :     fn prepare(
     294            0 :         tenant: &Tenant,
     295            0 :         timeline_id: TimelineId,
     296            0 :     ) -> Result<(Arc<Timeline>, DeletionGuard), DeleteTimelineError> {
     297            0 :         // Note the interaction between this guard and deletion guard.
     298            0 :         // Here we attempt to lock deletion guard when we're holding a lock on timelines.
     299            0 :         // This is important because when you take into account `remove_timeline_from_tenant`
     300            0 :         // we remove timeline from memory when we still hold the deletion guard.
     301            0 :         // So here when timeline deletion is finished timeline wont be present in timelines map at all
     302            0 :         // which makes the following sequence impossible:
     303            0 :         // T1: get preempted right before the try_lock on `Timeline::delete_progress`
     304            0 :         // T2: do a full deletion, acquire and drop `Timeline::delete_progress`
     305            0 :         // T1: acquire deletion lock, do another `DeleteTimelineFlow::run`
     306            0 :         // For more context see this discussion: `https://github.com/neondatabase/neon/pull/4552#discussion_r1253437346`
     307            0 :         let timelines = tenant.timelines.lock().unwrap();
     308              : 
     309            0 :         let timeline = match timelines.get(&timeline_id) {
     310            0 :             Some(t) => t,
     311            0 :             None => return Err(DeleteTimelineError::NotFound),
     312              :         };
     313              : 
     314              :         // Ensure that there are no child timelines **attached to that pageserver**,
     315              :         // because detach removes files, which will break child branches
     316            0 :         let children: Vec<TimelineId> = timelines
     317            0 :             .iter()
     318            0 :             .filter_map(|(id, entry)| {
     319            0 :                 if entry.get_ancestor_timeline_id() == Some(timeline_id) {
     320            0 :                     Some(*id)
     321              :                 } else {
     322            0 :                     None
     323              :                 }
     324            0 :             })
     325            0 :             .collect();
     326            0 : 
     327            0 :         if !children.is_empty() {
     328            0 :             return Err(DeleteTimelineError::HasChildren(children));
     329            0 :         }
     330            0 : 
     331            0 :         // Note that using try_lock here is important to avoid a deadlock.
     332            0 :         // Here we take lock on timelines and then the deletion guard.
     333            0 :         // At the end of the operation we're holding the guard and need to lock timelines map
     334            0 :         // to remove the timeline from it.
     335            0 :         // Always if you have two locks that are taken in different order this can result in a deadlock.
     336            0 : 
     337            0 :         let delete_progress = Arc::clone(&timeline.delete_progress);
     338            0 :         let delete_lock_guard = match delete_progress.try_lock_owned() {
     339            0 :             Ok(guard) => DeletionGuard(guard),
     340              :             Err(_) => {
     341              :                 // Unfortunately if lock fails arc is consumed.
     342            0 :                 return Err(DeleteTimelineError::AlreadyInProgress(Arc::clone(
     343            0 :                     &timeline.delete_progress,
     344            0 :                 )));
     345              :             }
     346              :         };
     347              : 
     348            0 :         timeline.set_state(TimelineState::Stopping);
     349            0 : 
     350            0 :         Ok((Arc::clone(timeline), delete_lock_guard))
     351            0 :     }
     352              : 
     353            0 :     fn schedule_background(
     354            0 :         guard: DeletionGuard,
     355            0 :         conf: &'static PageServerConf,
     356            0 :         tenant: Arc<Tenant>,
     357            0 :         timeline: Arc<Timeline>,
     358            0 :     ) {
     359            0 :         let tenant_shard_id = timeline.tenant_shard_id;
     360            0 :         let timeline_id = timeline.timeline_id;
     361            0 : 
     362            0 :         task_mgr::spawn(
     363            0 :             task_mgr::BACKGROUND_RUNTIME.handle(),
     364            0 :             TaskKind::TimelineDeletionWorker,
     365            0 :             tenant_shard_id,
     366            0 :             Some(timeline_id),
     367            0 :             "timeline_delete",
     368            0 :             async move {
     369            0 :                 if let Err(err) = Self::background(guard, conf, &tenant, &timeline).await {
     370            0 :                     error!("Error: {err:#}");
     371            0 :                     timeline.set_broken(format!("{err:#}"))
     372            0 :                 };
     373            0 :                 Ok(())
     374            0 :             }
     375            0 :             .instrument(tracing::info_span!(parent: None, "delete_timeline", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),timeline_id=%timeline_id)),
     376              :         );
     377            0 :     }
     378              : 
     379            0 :     async fn background(
     380            0 :         mut guard: DeletionGuard,
     381            0 :         conf: &PageServerConf,
     382            0 :         tenant: &Tenant,
     383            0 :         timeline: &Timeline,
     384            0 :     ) -> Result<(), DeleteTimelineError> {
     385            0 :         delete_local_timeline_directory(conf, tenant.tenant_shard_id, timeline).await?;
     386              : 
     387            0 :         delete_remote_layers_and_index(timeline).await?;
     388              : 
     389            0 :         pausable_failpoint!("in_progress_delete");
     390              : 
     391            0 :         remove_timeline_from_tenant(tenant, timeline, &guard).await?;
     392              : 
     393            0 :         *guard = Self::Finished;
     394            0 : 
     395            0 :         Ok(())
     396            0 :     }
     397              : 
     398            0 :     pub(crate) fn is_not_started(&self) -> bool {
     399            0 :         matches!(self, Self::NotStarted)
     400            0 :     }
     401              : }
     402              : 
     403              : struct DeletionGuard(OwnedMutexGuard<DeleteTimelineFlow>);
     404              : 
     405              : impl Deref for DeletionGuard {
     406              :     type Target = DeleteTimelineFlow;
     407              : 
     408            0 :     fn deref(&self) -> &Self::Target {
     409            0 :         &self.0
     410            0 :     }
     411              : }
     412              : 
     413              : impl DerefMut for DeletionGuard {
     414            0 :     fn deref_mut(&mut self) -> &mut Self::Target {
     415            0 :         &mut self.0
     416            0 :     }
     417              : }
        

Generated by: LCOV version 2.1-beta