LCOV - code coverage report
Current view: top level - pageserver/src/tenant/timeline - delete.rs (source / functions) Coverage Total Hit
Test: a43a77853355b937a79c57b07a8f05607cf29e6c.info Lines: 0.0 % 214 0
Test Date: 2024-09-19 12:04:32 Functions: 0.0 % 28 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              : // This function removs remaining traces of a timeline on disk.
     139              : // Namely: metadata file, timeline directory, delete mark.
     140              : // Note: io::ErrorKind::NotFound are ignored for metadata and timeline dir.
     141              : // delete mark should be present because it is the last step during deletion.
     142              : // (nothing can fail after its deletion)
     143            0 : async fn cleanup_remaining_timeline_fs_traces(
     144            0 :     conf: &PageServerConf,
     145            0 :     tenant_shard_id: TenantShardId,
     146            0 :     timeline_id: TimelineId,
     147            0 : ) -> anyhow::Result<()> {
     148            0 :     // Remove delete mark
     149            0 :     // TODO: once we are confident that no more exist in the field, remove this
     150            0 :     // line.  It cleans up a legacy marker file that might in rare cases be present.
     151            0 :     tokio::fs::remove_file(conf.timeline_delete_mark_file_path(tenant_shard_id, timeline_id))
     152            0 :         .await
     153            0 :         .or_else(fs_ext::ignore_not_found)
     154            0 :         .context("remove delete mark")
     155            0 : }
     156              : 
     157              : /// It is important that this gets called when DeletionGuard is being held.
     158              : /// For more context see comments in [`DeleteTimelineFlow::prepare`]
     159            0 : async fn remove_timeline_from_tenant(
     160            0 :     tenant: &Tenant,
     161            0 :     timeline: &Timeline,
     162            0 :     _: &DeletionGuard, // using it as a witness
     163            0 : ) -> anyhow::Result<()> {
     164            0 :     // Remove the timeline from the map.
     165            0 :     let mut timelines = tenant.timelines.lock().unwrap();
     166            0 :     let children_exist = timelines
     167            0 :         .iter()
     168            0 :         .any(|(_, entry)| entry.get_ancestor_timeline_id() == Some(timeline.timeline_id));
     169            0 :     // XXX this can happen because `branch_timeline` doesn't check `TimelineState::Stopping`.
     170            0 :     // We already deleted the layer files, so it's probably best to panic.
     171            0 :     // (Ideally, above remove_dir_all is atomic so we don't see this timeline after a restart)
     172            0 :     if children_exist {
     173            0 :         panic!("Timeline grew children while we removed layer files");
     174            0 :     }
     175            0 : 
     176            0 :     timelines
     177            0 :         .remove(&timeline.timeline_id)
     178            0 :         .expect("timeline that we were deleting was concurrently removed from 'timelines' map");
     179            0 : 
     180            0 :     drop(timelines);
     181            0 : 
     182            0 :     Ok(())
     183            0 : }
     184              : 
     185              : /// Orchestrates timeline shut down of all timeline tasks, removes its in-memory structures,
     186              : /// and deletes its data from both disk and s3.
     187              : /// The sequence of steps:
     188              : /// 1. Set deleted_at in remote index part.
     189              : /// 2. Create local mark file.
     190              : /// 3. Delete local files except metadata (it is simpler this way, to be able to reuse timeline initialization code that expects metadata)
     191              : /// 4. Delete remote layers
     192              : /// 5. Delete index part
     193              : /// 6. Delete meta, timeline directory
     194              : /// 7. Delete mark file
     195              : ///
     196              : /// It is resumable from any step in case a crash/restart occurs.
     197              : /// There are three entrypoints to the process:
     198              : /// 1. [`DeleteTimelineFlow::run`] this is the main one called by a management api handler.
     199              : /// 2. [`DeleteTimelineFlow::resume_deletion`] is called during restarts when local metadata is still present
     200              : ///    and we possibly neeed to continue deletion of remote files.
     201              : /// 3. [`DeleteTimelineFlow::cleanup_remaining_timeline_fs_traces`] is used when we deleted remote
     202              : ///    index but still have local metadata, timeline directory and delete mark.
     203              : ///
     204              : /// Note the only other place that messes around timeline delete mark is the logic that scans directory with timelines during tenant load.
     205              : #[derive(Default)]
     206              : pub enum DeleteTimelineFlow {
     207              :     #[default]
     208              :     NotStarted,
     209              :     InProgress,
     210              :     Finished,
     211              : }
     212              : 
     213              : impl DeleteTimelineFlow {
     214              :     // These steps are run in the context of management api request handler.
     215              :     // Long running steps are continued to run in the background.
     216              :     // NB: If this fails half-way through, and is retried, the retry will go through
     217              :     // all the same steps again. Make sure the code here is idempotent, and don't
     218              :     // error out if some of the shutdown tasks have already been completed!
     219            0 :     #[instrument(skip_all)]
     220              :     pub async fn run(
     221              :         tenant: &Arc<Tenant>,
     222              :         timeline_id: TimelineId,
     223              :     ) -> Result<(), DeleteTimelineError> {
     224              :         super::debug_assert_current_span_has_tenant_and_timeline_id();
     225              : 
     226              :         let (timeline, mut guard) = Self::prepare(tenant, timeline_id)?;
     227              : 
     228              :         guard.mark_in_progress()?;
     229              : 
     230              :         // Now that the Timeline is in Stopping state, request all the related tasks to shut down.
     231              :         timeline.shutdown(super::ShutdownMode::Hard).await;
     232              : 
     233              :         tenant.gc_block.before_delete(&timeline);
     234              : 
     235            0 :         fail::fail_point!("timeline-delete-before-index-deleted-at", |_| {
     236            0 :             Err(anyhow::anyhow!(
     237            0 :                 "failpoint: timeline-delete-before-index-deleted-at"
     238            0 :             ))?
     239            0 :         });
     240              : 
     241              :         set_deleted_in_remote_index(&timeline).await?;
     242              : 
     243            0 :         fail::fail_point!("timeline-delete-before-schedule", |_| {
     244            0 :             Err(anyhow::anyhow!(
     245            0 :                 "failpoint: timeline-delete-before-schedule"
     246            0 :             ))?
     247            0 :         });
     248              : 
     249              :         Self::schedule_background(guard, tenant.conf, Arc::clone(tenant), timeline);
     250              : 
     251              :         Ok(())
     252              :     }
     253              : 
     254            0 :     fn mark_in_progress(&mut self) -> anyhow::Result<()> {
     255            0 :         match self {
     256            0 :             Self::Finished => anyhow::bail!("Bug. Is in finished state"),
     257            0 :             Self::InProgress { .. } => { /* We're in a retry */ }
     258            0 :             Self::NotStarted => { /* Fresh start */ }
     259              :         }
     260              : 
     261            0 :         *self = Self::InProgress;
     262            0 : 
     263            0 :         Ok(())
     264            0 :     }
     265              : 
     266              :     /// Shortcut to create Timeline in stopping state and spawn deletion task.
     267            0 :     #[instrument(skip_all, fields(%timeline_id))]
     268              :     pub async fn resume_deletion(
     269              :         tenant: Arc<Tenant>,
     270              :         timeline_id: TimelineId,
     271              :         local_metadata: &TimelineMetadata,
     272              :         remote_client: RemoteTimelineClient,
     273              :     ) -> anyhow::Result<()> {
     274              :         // Note: here we even skip populating layer map. Timeline is essentially uninitialized.
     275              :         // RemoteTimelineClient is the only functioning part.
     276              :         let timeline = tenant
     277              :             .create_timeline_struct(
     278              :                 timeline_id,
     279              :                 local_metadata,
     280              :                 None, // Ancestor is not needed for deletion.
     281              :                 TimelineResources {
     282              :                     remote_client,
     283              :                     timeline_get_throttle: tenant.timeline_get_throttle.clone(),
     284              :                     l0_flush_global_state: tenant.l0_flush_global_state.clone(),
     285              :                 },
     286              :                 // Important. We dont pass ancestor above because it can be missing.
     287              :                 // Thus we need to skip the validation here.
     288              :                 CreateTimelineCause::Delete,
     289              :                 // Aux file policy is not needed for deletion, assuming deletion does not read aux keyspace
     290              :                 None,
     291              :             )
     292              :             .context("create_timeline_struct")?;
     293              : 
     294              :         let mut guard = DeletionGuard(
     295              :             Arc::clone(&timeline.delete_progress)
     296              :                 .try_lock_owned()
     297              :                 .expect("cannot happen because we're the only owner"),
     298              :         );
     299              : 
     300              :         // We meed to do this because when console retries delete request we shouldnt answer with 404
     301              :         // because 404 means successful deletion.
     302              :         {
     303              :             let mut locked = tenant.timelines.lock().unwrap();
     304              :             locked.insert(timeline_id, Arc::clone(&timeline));
     305              :         }
     306              : 
     307              :         guard.mark_in_progress()?;
     308              : 
     309              :         Self::schedule_background(guard, tenant.conf, tenant, timeline);
     310              : 
     311              :         Ok(())
     312              :     }
     313              : 
     314            0 :     #[instrument(skip_all, fields(%timeline_id))]
     315              :     pub async fn cleanup_remaining_timeline_fs_traces(
     316              :         tenant: &Tenant,
     317              :         timeline_id: TimelineId,
     318              :     ) -> anyhow::Result<()> {
     319              :         let r =
     320              :             cleanup_remaining_timeline_fs_traces(tenant.conf, tenant.tenant_shard_id, timeline_id)
     321              :                 .await;
     322              :         info!("Done");
     323              :         r
     324              :     }
     325              : 
     326            0 :     fn prepare(
     327            0 :         tenant: &Tenant,
     328            0 :         timeline_id: TimelineId,
     329            0 :     ) -> Result<(Arc<Timeline>, DeletionGuard), DeleteTimelineError> {
     330            0 :         // Note the interaction between this guard and deletion guard.
     331            0 :         // Here we attempt to lock deletion guard when we're holding a lock on timelines.
     332            0 :         // This is important because when you take into account `remove_timeline_from_tenant`
     333            0 :         // we remove timeline from memory when we still hold the deletion guard.
     334            0 :         // So here when timeline deletion is finished timeline wont be present in timelines map at all
     335            0 :         // which makes the following sequence impossible:
     336            0 :         // T1: get preempted right before the try_lock on `Timeline::delete_progress`
     337            0 :         // T2: do a full deletion, acquire and drop `Timeline::delete_progress`
     338            0 :         // T1: acquire deletion lock, do another `DeleteTimelineFlow::run`
     339            0 :         // For more context see this discussion: `https://github.com/neondatabase/neon/pull/4552#discussion_r1253437346`
     340            0 :         let timelines = tenant.timelines.lock().unwrap();
     341              : 
     342            0 :         let timeline = match timelines.get(&timeline_id) {
     343            0 :             Some(t) => t,
     344            0 :             None => return Err(DeleteTimelineError::NotFound),
     345              :         };
     346              : 
     347              :         // Ensure that there are no child timelines **attached to that pageserver**,
     348              :         // because detach removes files, which will break child branches
     349            0 :         let children: Vec<TimelineId> = timelines
     350            0 :             .iter()
     351            0 :             .filter_map(|(id, entry)| {
     352            0 :                 if entry.get_ancestor_timeline_id() == Some(timeline_id) {
     353            0 :                     Some(*id)
     354              :                 } else {
     355            0 :                     None
     356              :                 }
     357            0 :             })
     358            0 :             .collect();
     359            0 : 
     360            0 :         if !children.is_empty() {
     361            0 :             return Err(DeleteTimelineError::HasChildren(children));
     362            0 :         }
     363            0 : 
     364            0 :         // Note that using try_lock here is important to avoid a deadlock.
     365            0 :         // Here we take lock on timelines and then the deletion guard.
     366            0 :         // At the end of the operation we're holding the guard and need to lock timelines map
     367            0 :         // to remove the timeline from it.
     368            0 :         // Always if you have two locks that are taken in different order this can result in a deadlock.
     369            0 : 
     370            0 :         let delete_progress = Arc::clone(&timeline.delete_progress);
     371            0 :         let delete_lock_guard = match delete_progress.try_lock_owned() {
     372            0 :             Ok(guard) => DeletionGuard(guard),
     373              :             Err(_) => {
     374              :                 // Unfortunately if lock fails arc is consumed.
     375            0 :                 return Err(DeleteTimelineError::AlreadyInProgress(Arc::clone(
     376            0 :                     &timeline.delete_progress,
     377            0 :                 )));
     378              :             }
     379              :         };
     380              : 
     381            0 :         timeline.set_state(TimelineState::Stopping);
     382            0 : 
     383            0 :         Ok((Arc::clone(timeline), delete_lock_guard))
     384            0 :     }
     385              : 
     386            0 :     fn schedule_background(
     387            0 :         guard: DeletionGuard,
     388            0 :         conf: &'static PageServerConf,
     389            0 :         tenant: Arc<Tenant>,
     390            0 :         timeline: Arc<Timeline>,
     391            0 :     ) {
     392            0 :         let tenant_shard_id = timeline.tenant_shard_id;
     393            0 :         let timeline_id = timeline.timeline_id;
     394            0 : 
     395            0 :         task_mgr::spawn(
     396            0 :             task_mgr::BACKGROUND_RUNTIME.handle(),
     397            0 :             TaskKind::TimelineDeletionWorker,
     398            0 :             tenant_shard_id,
     399            0 :             Some(timeline_id),
     400            0 :             "timeline_delete",
     401            0 :             async move {
     402            0 :                 if let Err(err) = Self::background(guard, conf, &tenant, &timeline).await {
     403            0 :                     error!("Error: {err:#}");
     404            0 :                     timeline.set_broken(format!("{err:#}"))
     405            0 :                 };
     406            0 :                 Ok(())
     407            0 :             }
     408            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)),
     409              :         );
     410            0 :     }
     411              : 
     412            0 :     async fn background(
     413            0 :         mut guard: DeletionGuard,
     414            0 :         conf: &PageServerConf,
     415            0 :         tenant: &Tenant,
     416            0 :         timeline: &Timeline,
     417            0 :     ) -> Result<(), DeleteTimelineError> {
     418            0 :         delete_local_timeline_directory(conf, tenant.tenant_shard_id, timeline).await?;
     419              : 
     420            0 :         delete_remote_layers_and_index(timeline).await?;
     421              : 
     422            0 :         pausable_failpoint!("in_progress_delete");
     423              : 
     424            0 :         remove_timeline_from_tenant(tenant, timeline, &guard).await?;
     425              : 
     426            0 :         *guard = Self::Finished;
     427            0 : 
     428            0 :         Ok(())
     429            0 :     }
     430              : 
     431            0 :     pub(crate) fn is_not_started(&self) -> bool {
     432            0 :         matches!(self, Self::NotStarted)
     433            0 :     }
     434              : }
     435              : 
     436              : struct DeletionGuard(OwnedMutexGuard<DeleteTimelineFlow>);
     437              : 
     438              : impl Deref for DeletionGuard {
     439              :     type Target = DeleteTimelineFlow;
     440              : 
     441            0 :     fn deref(&self) -> &Self::Target {
     442            0 :         &self.0
     443            0 :     }
     444              : }
     445              : 
     446              : impl DerefMut for DeletionGuard {
     447            0 :     fn deref_mut(&mut self) -> &mut Self::Target {
     448            0 :         &mut self.0
     449            0 :     }
     450              : }
        

Generated by: LCOV version 2.1-beta