LCOV - code coverage report
Current view: top level - pageserver/src/tenant/timeline - delete.rs (source / functions) Coverage Total Hit
Test: 190869232aac3a234374e5bb62582e91cf5f5818.info Lines: 0.3 % 299 1
Test Date: 2024-02-23 13:21:27 Functions: 1.7 % 59 1

            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::{debug, error, info, instrument, warn, Instrument};
      10              : use utils::{crashsafe, fs_ext, id::TimelineId};
      11              : 
      12              : use crate::{
      13              :     config::PageServerConf,
      14              :     deletion_queue::DeletionQueueClient,
      15              :     task_mgr::{self, TaskKind},
      16              :     tenant::{
      17              :         debug_assert_current_span_has_tenant_and_timeline_id,
      18              :         metadata::TimelineMetadata,
      19              :         remote_timeline_client::{
      20              :             self, PersistIndexPartWithDeletedFlagError, RemoteTimelineClient,
      21              :         },
      22              :         CreateTimelineCause, DeleteTimelineError, Tenant,
      23              :     },
      24              : };
      25              : 
      26              : use super::{Timeline, TimelineResources};
      27              : 
      28              : /// Now that the Timeline is in Stopping state, request all the related tasks to shut down.
      29            0 : async fn stop_tasks(timeline: &Timeline) -> Result<(), DeleteTimelineError> {
      30            0 :     debug_assert_current_span_has_tenant_and_timeline_id();
      31              :     // Notify any timeline work to drop out of loops/requests
      32            0 :     tracing::debug!("Cancelling CancellationToken");
      33            0 :     timeline.cancel.cancel();
      34              : 
      35              :     // Stop the walreceiver first.
      36            0 :     debug!("waiting for wal receiver to shutdown");
      37            0 :     let maybe_started_walreceiver = { timeline.walreceiver.lock().unwrap().take() };
      38            0 :     if let Some(walreceiver) = maybe_started_walreceiver {
      39            0 :         walreceiver.stop().await;
      40            0 :     }
      41            0 :     debug!("wal receiver shutdown confirmed");
      42              : 
      43              :     // Shut down the layer flush task before the remote client, as one depends on the other
      44            0 :     task_mgr::shutdown_tasks(
      45            0 :         Some(TaskKind::LayerFlushTask),
      46            0 :         Some(timeline.tenant_shard_id),
      47            0 :         Some(timeline.timeline_id),
      48            0 :     )
      49            0 :     .await;
      50              : 
      51              :     // Prevent new uploads from starting.
      52            0 :     if let Some(remote_client) = timeline.remote_client.as_ref() {
      53            0 :         let res = remote_client.stop();
      54            0 :         match res {
      55            0 :             Ok(()) => {}
      56            0 :             Err(e) => match e {
      57            0 :                 remote_timeline_client::StopError::QueueUninitialized => {
      58            0 :                     // This case shouldn't happen currently because the
      59            0 :                     // load and attach code bails out if _any_ of the timeline fails to fetch its IndexPart.
      60            0 :                     // That is, before we declare the Tenant as Active.
      61            0 :                     // But we only allow calls to delete_timeline on Active tenants.
      62            0 :                     return Err(DeleteTimelineError::Other(anyhow::anyhow!("upload queue is uninitialized, likely the timeline was in Broken state prior to this call because it failed to fetch IndexPart during load or attach, check the logs")));
      63              :                 }
      64              :             },
      65              :         }
      66            0 :     }
      67              : 
      68              :     // Stop & wait for the remaining timeline tasks, including upload tasks.
      69              :     // NB: This and other delete_timeline calls do not run as a task_mgr task,
      70              :     //     so, they are not affected by this shutdown_tasks() call.
      71            0 :     info!("waiting for timeline tasks to shutdown");
      72            0 :     task_mgr::shutdown_tasks(
      73            0 :         None,
      74            0 :         Some(timeline.tenant_shard_id),
      75            0 :         Some(timeline.timeline_id),
      76            0 :     )
      77            0 :     .await;
      78              : 
      79            0 :     fail::fail_point!("timeline-delete-before-index-deleted-at", |_| {
      80            0 :         Err(anyhow::anyhow!(
      81            0 :             "failpoint: timeline-delete-before-index-deleted-at"
      82            0 :         ))?
      83            0 :     });
      84              : 
      85            0 :     tracing::debug!("Waiting for gate...");
      86            0 :     timeline.gate.close().await;
      87            0 :     tracing::debug!("Shutdown complete");
      88              : 
      89            0 :     Ok(())
      90            0 : }
      91              : 
      92              : /// Mark timeline as deleted in S3 so we won't pick it up next time
      93              : /// during attach or pageserver restart.
      94              : /// See comment in persist_index_part_with_deleted_flag.
      95            0 : async fn set_deleted_in_remote_index(timeline: &Timeline) -> Result<(), DeleteTimelineError> {
      96            0 :     if let Some(remote_client) = timeline.remote_client.as_ref() {
      97            0 :         match remote_client.persist_index_part_with_deleted_flag().await {
      98              :             // If we (now, or already) marked it successfully as deleted, we can proceed
      99            0 :             Ok(()) | Err(PersistIndexPartWithDeletedFlagError::AlreadyDeleted(_)) => (),
     100              :             // Bail out otherwise
     101              :             //
     102              :             // AlreadyInProgress shouldn't happen, because the 'delete_lock' prevents
     103              :             // two tasks from performing the deletion at the same time. The first task
     104              :             // that starts deletion should run it to completion.
     105            0 :             Err(e @ PersistIndexPartWithDeletedFlagError::AlreadyInProgress(_))
     106            0 :             | Err(e @ PersistIndexPartWithDeletedFlagError::Other(_)) => {
     107            0 :                 return Err(DeleteTimelineError::Other(anyhow::anyhow!(e)));
     108              :             }
     109              :         }
     110            0 :     }
     111            0 :     Ok(())
     112            0 : }
     113              : 
     114              : /// Grab the compaction and gc locks, and actually perform the deletion.
     115              : ///
     116              : /// The locks prevent GC or compaction from running at the same time. The background tasks do not
     117              : /// register themselves with the timeline it's operating on, so it might still be running even
     118              : /// though we called `shutdown_tasks`.
     119              : ///
     120              : /// Note that there are still other race conditions between
     121              : /// GC, compaction and timeline deletion. See
     122              : /// <https://github.com/neondatabase/neon/issues/2671>
     123              : ///
     124              : /// No timeout here, GC & Compaction should be responsive to the
     125              : /// `TimelineState::Stopping` change.
     126              : // pub(super): documentation link
     127            0 : pub(super) async fn delete_local_layer_files(
     128            0 :     conf: &PageServerConf,
     129            0 :     tenant_shard_id: TenantShardId,
     130            0 :     timeline: &Timeline,
     131            0 : ) -> anyhow::Result<()> {
     132            0 :     let guards = async { tokio::join!(timeline.gc_lock.lock(), timeline.compaction_lock.lock()) };
     133            0 :     let guards = crate::timed(
     134            0 :         guards,
     135            0 :         "acquire gc and compaction locks",
     136            0 :         std::time::Duration::from_secs(5),
     137            0 :     )
     138            0 :     .await;
     139              : 
     140              :     // NB: storage_sync upload tasks that reference these layers have been cancelled
     141              :     //     by the caller.
     142              : 
     143            0 :     let local_timeline_directory = conf.timeline_path(&tenant_shard_id, &timeline.timeline_id);
     144            0 : 
     145            0 :     fail::fail_point!("timeline-delete-before-rm", |_| {
     146            0 :         Err(anyhow::anyhow!("failpoint: timeline-delete-before-rm"))?
     147            0 :     });
     148              : 
     149              :     // NB: This need not be atomic because the deleted flag in the IndexPart
     150              :     // will be observed during tenant/timeline load. The deletion will be resumed there.
     151              :     //
     152              :     // For configurations without remote storage, we guarantee crash-safety by persising delete mark file.
     153              :     //
     154              :     // Note that here we do not bail out on std::io::ErrorKind::NotFound.
     155              :     // This can happen if we're called a second time, e.g.,
     156              :     // because of a previous failure/cancellation at/after
     157              :     // failpoint timeline-delete-after-rm.
     158              :     //
     159              :     // ErrorKind::NotFound can also happen if we race with tenant detach, because,
     160              :     // no locks are shared.
     161              :     //
     162              :     // For now, log and continue.
     163              :     // warn! level is technically not appropriate for the
     164              :     // first case because we should expect retries to happen.
     165              :     // But the error is so rare, it seems better to get attention if it happens.
     166              :     //
     167              :     // Note that metadata removal is skipped, this is not technically needed,
     168              :     // but allows to reuse timeline loading code during resumed deletion.
     169              :     // (we always expect that metadata is in place when timeline is being loaded)
     170              : 
     171              :     #[cfg(feature = "testing")]
     172            0 :     let mut counter = 0;
     173            0 : 
     174            0 :     // Timeline directory may not exist if we failed to delete mark file and request was retried.
     175            0 :     if !local_timeline_directory.exists() {
     176            0 :         return Ok(());
     177            0 :     }
     178            0 : 
     179            0 :     let metadata_path = conf.metadata_path(&tenant_shard_id, &timeline.timeline_id);
     180              : 
     181            0 :     for entry in walkdir::WalkDir::new(&local_timeline_directory).contents_first(true) {
     182              :         #[cfg(feature = "testing")]
     183              :         {
     184            0 :             counter += 1;
     185            0 :             if counter == 2 {
     186            0 :                 fail::fail_point!("timeline-delete-during-rm", |_| {
     187            0 :                     Err(anyhow::anyhow!("failpoint: timeline-delete-during-rm"))?
     188            0 :                 });
     189            0 :             }
     190              :         }
     191              : 
     192            0 :         let entry = entry?;
     193            0 :         if entry.path() == metadata_path {
     194            0 :             debug!("found metadata, skipping");
     195            0 :             continue;
     196            0 :         }
     197            0 : 
     198            0 :         if entry.path() == local_timeline_directory {
     199              :             // Keeping directory because metedata file is still there
     200            0 :             debug!("found timeline dir itself, skipping");
     201            0 :             continue;
     202            0 :         }
     203              : 
     204            0 :         let metadata = match entry.metadata() {
     205            0 :             Ok(metadata) => metadata,
     206            0 :             Err(e) => {
     207            0 :                 if crate::is_walkdir_io_not_found(&e) {
     208            0 :                     warn!(
     209            0 :                         timeline_dir=?local_timeline_directory,
     210            0 :                         path=?entry.path().display(),
     211            0 :                         "got not found err while removing timeline dir, proceeding anyway"
     212            0 :                     );
     213            0 :                     continue;
     214            0 :                 }
     215            0 :                 anyhow::bail!(e);
     216              :             }
     217              :         };
     218              : 
     219            0 :         if metadata.is_dir() {
     220            0 :             warn!(path=%entry.path().display(), "unexpected directory under timeline dir");
     221            0 :             tokio::fs::remove_dir(entry.path()).await
     222              :         } else {
     223            0 :             tokio::fs::remove_file(entry.path()).await
     224              :         }
     225            0 :         .with_context(|| format!("Failed to remove: {}", entry.path().display()))?;
     226              :     }
     227              : 
     228            0 :     info!("finished deleting layer files, releasing locks");
     229            0 :     drop(guards);
     230            0 : 
     231            0 :     fail::fail_point!("timeline-delete-after-rm", |_| {
     232            0 :         Err(anyhow::anyhow!("failpoint: timeline-delete-after-rm"))?
     233            0 :     });
     234              : 
     235            0 :     Ok(())
     236            0 : }
     237              : 
     238              : /// Removes remote layers and an index file after them.
     239            0 : async fn delete_remote_layers_and_index(timeline: &Timeline) -> anyhow::Result<()> {
     240            0 :     if let Some(remote_client) = &timeline.remote_client {
     241            0 :         remote_client.delete_all().await.context("delete_all")?
     242            0 :     };
     243              : 
     244            0 :     Ok(())
     245            0 : }
     246              : 
     247              : // This function removs remaining traces of a timeline on disk.
     248              : // Namely: metadata file, timeline directory, delete mark.
     249              : // Note: io::ErrorKind::NotFound are ignored for metadata and timeline dir.
     250              : // delete mark should be present because it is the last step during deletion.
     251              : // (nothing can fail after its deletion)
     252            0 : async fn cleanup_remaining_timeline_fs_traces(
     253            0 :     conf: &PageServerConf,
     254            0 :     tenant_shard_id: TenantShardId,
     255            0 :     timeline_id: TimelineId,
     256            0 : ) -> anyhow::Result<()> {
     257            0 :     // Remove local metadata
     258            0 :     tokio::fs::remove_file(conf.metadata_path(&tenant_shard_id, &timeline_id))
     259            0 :         .await
     260            0 :         .or_else(fs_ext::ignore_not_found)
     261            0 :         .context("remove metadata")?;
     262              : 
     263            0 :     fail::fail_point!("timeline-delete-after-rm-metadata", |_| {
     264            0 :         Err(anyhow::anyhow!(
     265            0 :             "failpoint: timeline-delete-after-rm-metadata"
     266            0 :         ))?
     267            0 :     });
     268              : 
     269              :     // Remove timeline dir
     270            0 :     tokio::fs::remove_dir(conf.timeline_path(&tenant_shard_id, &timeline_id))
     271            0 :         .await
     272            0 :         .or_else(fs_ext::ignore_not_found)
     273            0 :         .context("timeline dir")?;
     274              : 
     275            0 :     fail::fail_point!("timeline-delete-after-rm-dir", |_| {
     276            0 :         Err(anyhow::anyhow!("failpoint: timeline-delete-after-rm-dir"))?
     277            0 :     });
     278              : 
     279              :     // Make sure previous deletions are ordered before mark removal.
     280              :     // Otherwise there is no guarantee that they reach the disk before mark deletion.
     281              :     // So its possible for mark to reach disk first and for other deletions
     282              :     // to be reordered later and thus missed if a crash occurs.
     283              :     // Note that we dont need to sync after mark file is removed
     284              :     // because we can tolerate the case when mark file reappears on startup.
     285            0 :     let timeline_path = conf.timelines_path(&tenant_shard_id);
     286            0 :     crashsafe::fsync_async(timeline_path)
     287            0 :         .await
     288            0 :         .context("fsync_pre_mark_remove")?;
     289              : 
     290              :     // Remove delete mark
     291              :     // TODO: once we are confident that no more exist in the field, remove this
     292              :     // line.  It cleans up a legacy marker file that might in rare cases be present.
     293            0 :     tokio::fs::remove_file(conf.timeline_delete_mark_file_path(tenant_shard_id, timeline_id))
     294            0 :         .await
     295            0 :         .or_else(fs_ext::ignore_not_found)
     296            0 :         .context("remove delete mark")
     297            0 : }
     298              : 
     299              : /// It is important that this gets called when DeletionGuard is being held.
     300              : /// For more context see comments in [`DeleteTimelineFlow::prepare`]
     301            0 : async fn remove_timeline_from_tenant(
     302            0 :     tenant: &Tenant,
     303            0 :     timeline_id: TimelineId,
     304            0 :     _: &DeletionGuard, // using it as a witness
     305            0 : ) -> anyhow::Result<()> {
     306            0 :     // Remove the timeline from the map.
     307            0 :     let mut timelines = tenant.timelines.lock().unwrap();
     308            0 :     let children_exist = timelines
     309            0 :         .iter()
     310            0 :         .any(|(_, entry)| entry.get_ancestor_timeline_id() == Some(timeline_id));
     311            0 :     // XXX this can happen because `branch_timeline` doesn't check `TimelineState::Stopping`.
     312            0 :     // We already deleted the layer files, so it's probably best to panic.
     313            0 :     // (Ideally, above remove_dir_all is atomic so we don't see this timeline after a restart)
     314            0 :     if children_exist {
     315            0 :         panic!("Timeline grew children while we removed layer files");
     316            0 :     }
     317            0 : 
     318            0 :     timelines
     319            0 :         .remove(&timeline_id)
     320            0 :         .expect("timeline that we were deleting was concurrently removed from 'timelines' map");
     321            0 : 
     322            0 :     drop(timelines);
     323            0 : 
     324            0 :     Ok(())
     325            0 : }
     326              : 
     327              : /// Orchestrates timeline shut down of all timeline tasks, removes its in-memory structures,
     328              : /// and deletes its data from both disk and s3.
     329              : /// The sequence of steps:
     330              : /// 1. Set deleted_at in remote index part.
     331              : /// 2. Create local mark file.
     332              : /// 3. Delete local files except metadata (it is simpler this way, to be able to reuse timeline initialization code that expects metadata)
     333              : /// 4. Delete remote layers
     334              : /// 5. Delete index part
     335              : /// 6. Delete meta, timeline directory
     336              : /// 7. Delete mark file
     337              : /// It is resumable from any step in case a crash/restart occurs.
     338              : /// There are three entrypoints to the process:
     339              : /// 1. [`DeleteTimelineFlow::run`] this is the main one called by a management api handler.
     340              : /// 2. [`DeleteTimelineFlow::resume_deletion`] is called during restarts when local metadata is still present
     341              : /// and we possibly neeed to continue deletion of remote files.
     342              : /// 3. [`DeleteTimelineFlow::cleanup_remaining_timeline_fs_traces`] is used when we deleted remote
     343              : /// index but still have local metadata, timeline directory and delete mark.
     344              : /// Note the only other place that messes around timeline delete mark is the logic that scans directory with timelines during tenant load.
     345          292 : #[derive(Default)]
     346              : pub enum DeleteTimelineFlow {
     347              :     #[default]
     348              :     NotStarted,
     349              :     InProgress,
     350              :     Finished,
     351              : }
     352              : 
     353              : impl DeleteTimelineFlow {
     354              :     // These steps are run in the context of management api request handler.
     355              :     // Long running steps are continued to run in the background.
     356              :     // NB: If this fails half-way through, and is retried, the retry will go through
     357              :     // all the same steps again. Make sure the code here is idempotent, and don't
     358              :     // error out if some of the shutdown tasks have already been completed!
     359            0 :     #[instrument(skip_all, fields(%inplace))]
     360              :     pub async fn run(
     361              :         tenant: &Arc<Tenant>,
     362              :         timeline_id: TimelineId,
     363              :         inplace: bool,
     364              :     ) -> Result<(), DeleteTimelineError> {
     365              :         super::debug_assert_current_span_has_tenant_and_timeline_id();
     366              : 
     367              :         let (timeline, mut guard) = Self::prepare(tenant, timeline_id)?;
     368              : 
     369              :         guard.mark_in_progress()?;
     370              : 
     371              :         stop_tasks(&timeline).await?;
     372              : 
     373              :         set_deleted_in_remote_index(&timeline).await?;
     374              : 
     375            0 :         fail::fail_point!("timeline-delete-before-schedule", |_| {
     376            0 :             Err(anyhow::anyhow!(
     377            0 :                 "failpoint: timeline-delete-before-schedule"
     378            0 :             ))?
     379            0 :         });
     380              : 
     381              :         if inplace {
     382              :             Self::background(guard, tenant.conf, tenant, &timeline).await?
     383              :         } else {
     384              :             Self::schedule_background(guard, tenant.conf, Arc::clone(tenant), timeline);
     385              :         }
     386              : 
     387              :         Ok(())
     388              :     }
     389              : 
     390            0 :     fn mark_in_progress(&mut self) -> anyhow::Result<()> {
     391            0 :         match self {
     392            0 :             Self::Finished => anyhow::bail!("Bug. Is in finished state"),
     393            0 :             Self::InProgress { .. } => { /* We're in a retry */ }
     394            0 :             Self::NotStarted => { /* Fresh start */ }
     395              :         }
     396              : 
     397            0 :         *self = Self::InProgress;
     398            0 : 
     399            0 :         Ok(())
     400            0 :     }
     401              : 
     402              :     /// Shortcut to create Timeline in stopping state and spawn deletion task.
     403              :     /// See corresponding parts of [`crate::tenant::delete::DeleteTenantFlow`]
     404            0 :     #[instrument(skip_all, fields(%timeline_id))]
     405              :     pub async fn resume_deletion(
     406              :         tenant: Arc<Tenant>,
     407              :         timeline_id: TimelineId,
     408              :         local_metadata: &TimelineMetadata,
     409              :         remote_client: Option<RemoteTimelineClient>,
     410              :         deletion_queue_client: DeletionQueueClient,
     411              :     ) -> anyhow::Result<()> {
     412              :         // Note: here we even skip populating layer map. Timeline is essentially uninitialized.
     413              :         // RemoteTimelineClient is the only functioning part.
     414              :         let timeline = tenant
     415              :             .create_timeline_struct(
     416              :                 timeline_id,
     417              :                 local_metadata,
     418              :                 None, // Ancestor is not needed for deletion.
     419              :                 TimelineResources {
     420              :                     remote_client,
     421              :                     deletion_queue_client,
     422              :                     timeline_get_throttle: tenant.timeline_get_throttle.clone(),
     423              :                 },
     424              :                 // Important. We dont pass ancestor above because it can be missing.
     425              :                 // Thus we need to skip the validation here.
     426              :                 CreateTimelineCause::Delete,
     427              :             )
     428              :             .context("create_timeline_struct")?;
     429              : 
     430              :         let mut guard = DeletionGuard(
     431              :             Arc::clone(&timeline.delete_progress)
     432              :                 .try_lock_owned()
     433              :                 .expect("cannot happen because we're the only owner"),
     434              :         );
     435              : 
     436              :         // We meed to do this because when console retries delete request we shouldnt answer with 404
     437              :         // because 404 means successful deletion.
     438              :         {
     439              :             let mut locked = tenant.timelines.lock().unwrap();
     440              :             locked.insert(timeline_id, Arc::clone(&timeline));
     441              :         }
     442              : 
     443              :         guard.mark_in_progress()?;
     444              : 
     445              :         Self::schedule_background(guard, tenant.conf, tenant, timeline);
     446              : 
     447              :         Ok(())
     448              :     }
     449              : 
     450            0 :     #[instrument(skip_all, fields(%timeline_id))]
     451              :     pub async fn cleanup_remaining_timeline_fs_traces(
     452              :         tenant: &Tenant,
     453              :         timeline_id: TimelineId,
     454              :     ) -> anyhow::Result<()> {
     455              :         let r =
     456              :             cleanup_remaining_timeline_fs_traces(tenant.conf, tenant.tenant_shard_id, timeline_id)
     457              :                 .await;
     458            0 :         info!("Done");
     459              :         r
     460              :     }
     461              : 
     462            0 :     fn prepare(
     463            0 :         tenant: &Tenant,
     464            0 :         timeline_id: TimelineId,
     465            0 :     ) -> Result<(Arc<Timeline>, DeletionGuard), DeleteTimelineError> {
     466            0 :         // Note the interaction between this guard and deletion guard.
     467            0 :         // Here we attempt to lock deletion guard when we're holding a lock on timelines.
     468            0 :         // This is important because when you take into account `remove_timeline_from_tenant`
     469            0 :         // we remove timeline from memory when we still hold the deletion guard.
     470            0 :         // So here when timeline deletion is finished timeline wont be present in timelines map at all
     471            0 :         // which makes the following sequence impossible:
     472            0 :         // T1: get preempted right before the try_lock on `Timeline::delete_progress`
     473            0 :         // T2: do a full deletion, acquire and drop `Timeline::delete_progress`
     474            0 :         // T1: acquire deletion lock, do another `DeleteTimelineFlow::run`
     475            0 :         // For more context see this discussion: `https://github.com/neondatabase/neon/pull/4552#discussion_r1253437346`
     476            0 :         let timelines = tenant.timelines.lock().unwrap();
     477              : 
     478            0 :         let timeline = match timelines.get(&timeline_id) {
     479            0 :             Some(t) => t,
     480            0 :             None => return Err(DeleteTimelineError::NotFound),
     481              :         };
     482              : 
     483              :         // Ensure that there are no child timelines **attached to that pageserver**,
     484              :         // because detach removes files, which will break child branches
     485            0 :         let children: Vec<TimelineId> = timelines
     486            0 :             .iter()
     487            0 :             .filter_map(|(id, entry)| {
     488            0 :                 if entry.get_ancestor_timeline_id() == Some(timeline_id) {
     489            0 :                     Some(*id)
     490              :                 } else {
     491            0 :                     None
     492              :                 }
     493            0 :             })
     494            0 :             .collect();
     495            0 : 
     496            0 :         if !children.is_empty() {
     497            0 :             return Err(DeleteTimelineError::HasChildren(children));
     498            0 :         }
     499            0 : 
     500            0 :         // Note that using try_lock here is important to avoid a deadlock.
     501            0 :         // Here we take lock on timelines and then the deletion guard.
     502            0 :         // At the end of the operation we're holding the guard and need to lock timelines map
     503            0 :         // to remove the timeline from it.
     504            0 :         // Always if you have two locks that are taken in different order this can result in a deadlock.
     505            0 : 
     506            0 :         let delete_progress = Arc::clone(&timeline.delete_progress);
     507            0 :         let delete_lock_guard = match delete_progress.try_lock_owned() {
     508            0 :             Ok(guard) => DeletionGuard(guard),
     509              :             Err(_) => {
     510              :                 // Unfortunately if lock fails arc is consumed.
     511            0 :                 return Err(DeleteTimelineError::AlreadyInProgress(Arc::clone(
     512            0 :                     &timeline.delete_progress,
     513            0 :                 )));
     514              :             }
     515              :         };
     516              : 
     517            0 :         timeline.set_state(TimelineState::Stopping);
     518            0 : 
     519            0 :         Ok((Arc::clone(timeline), delete_lock_guard))
     520            0 :     }
     521              : 
     522            0 :     fn schedule_background(
     523            0 :         guard: DeletionGuard,
     524            0 :         conf: &'static PageServerConf,
     525            0 :         tenant: Arc<Tenant>,
     526            0 :         timeline: Arc<Timeline>,
     527            0 :     ) {
     528            0 :         let tenant_shard_id = timeline.tenant_shard_id;
     529            0 :         let timeline_id = timeline.timeline_id;
     530            0 : 
     531            0 :         task_mgr::spawn(
     532            0 :             task_mgr::BACKGROUND_RUNTIME.handle(),
     533            0 :             TaskKind::TimelineDeletionWorker,
     534            0 :             Some(tenant_shard_id),
     535            0 :             Some(timeline_id),
     536            0 :             "timeline_delete",
     537              :             false,
     538            0 :             async move {
     539            0 :                 if let Err(err) = Self::background(guard, conf, &tenant, &timeline).await {
     540            0 :                     error!("Error: {err:#}");
     541            0 :                     timeline.set_broken(format!("{err:#}"))
     542            0 :                 };
     543            0 :                 Ok(())
     544            0 :             }
     545            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)),
     546              :         );
     547            0 :     }
     548              : 
     549            0 :     async fn background(
     550            0 :         mut guard: DeletionGuard,
     551            0 :         conf: &PageServerConf,
     552            0 :         tenant: &Tenant,
     553            0 :         timeline: &Timeline,
     554            0 :     ) -> Result<(), DeleteTimelineError> {
     555            0 :         delete_local_layer_files(conf, tenant.tenant_shard_id, timeline).await?;
     556              : 
     557            0 :         delete_remote_layers_and_index(timeline).await?;
     558              : 
     559            0 :         pausable_failpoint!("in_progress_delete");
     560              : 
     561            0 :         cleanup_remaining_timeline_fs_traces(conf, tenant.tenant_shard_id, timeline.timeline_id)
     562            0 :             .await?;
     563              : 
     564            0 :         remove_timeline_from_tenant(tenant, timeline.timeline_id, &guard).await?;
     565              : 
     566            0 :         *guard = Self::Finished;
     567            0 : 
     568            0 :         Ok(())
     569            0 :     }
     570              : 
     571            0 :     pub(crate) fn is_finished(&self) -> bool {
     572            0 :         matches!(self, Self::Finished)
     573            0 :     }
     574              : }
     575              : 
     576              : struct DeletionGuard(OwnedMutexGuard<DeleteTimelineFlow>);
     577              : 
     578              : impl Deref for DeletionGuard {
     579              :     type Target = DeleteTimelineFlow;
     580              : 
     581            0 :     fn deref(&self) -> &Self::Target {
     582            0 :         &self.0
     583            0 :     }
     584              : }
     585              : 
     586              : impl DerefMut for DeletionGuard {
     587            0 :     fn deref_mut(&mut self) -> &mut Self::Target {
     588            0 :         &mut self.0
     589            0 :     }
     590              : }
        

Generated by: LCOV version 2.1-beta