LCOV - code coverage report
Current view: top level - pageserver/src/tenant/timeline - detach_ancestor.rs (source / functions) Coverage Total Hit
Test: ae4948feae6a1d420c855050eb8c189119446a71.info Lines: 0.0 % 789 0
Test Date: 2025-03-18 18:33:46 Functions: 0.0 % 72 0

            Line data    Source code
       1              : use std::collections::HashSet;
       2              : use std::sync::Arc;
       3              : 
       4              : use anyhow::Context;
       5              : use http_utils::error::ApiError;
       6              : use pageserver_api::models::DetachBehavior;
       7              : use pageserver_api::models::detach_ancestor::AncestorDetached;
       8              : use pageserver_api::shard::ShardIdentity;
       9              : use tokio::sync::Semaphore;
      10              : use tokio_util::sync::CancellationToken;
      11              : use tracing::Instrument;
      12              : use utils::completion;
      13              : use utils::generation::Generation;
      14              : use utils::id::TimelineId;
      15              : use utils::lsn::Lsn;
      16              : use utils::sync::gate::GateError;
      17              : 
      18              : use super::layer_manager::LayerManager;
      19              : use super::{FlushLayerError, Timeline};
      20              : use crate::context::{DownloadBehavior, RequestContext};
      21              : use crate::task_mgr::TaskKind;
      22              : use crate::tenant::Tenant;
      23              : use crate::tenant::remote_timeline_client::index::GcBlockingReason::DetachAncestor;
      24              : use crate::tenant::storage_layer::layer::local_layer_path;
      25              : use crate::tenant::storage_layer::{AsLayerDesc as _, DeltaLayerWriter, Layer, ResidentLayer};
      26              : use crate::virtual_file::{MaybeFatalIo, VirtualFile};
      27              : 
      28              : #[derive(Debug, thiserror::Error)]
      29              : pub(crate) enum Error {
      30              :     #[error("no ancestors")]
      31              :     NoAncestor,
      32              : 
      33              :     #[error("too many ancestors")]
      34              :     TooManyAncestors,
      35              : 
      36              :     #[error("ancestor is not empty")]
      37              :     AncestorNotEmpty,
      38              : 
      39              :     #[error("shutting down, please retry later")]
      40              :     ShuttingDown,
      41              : 
      42              :     #[error("archived: {}", .0)]
      43              :     Archived(TimelineId),
      44              : 
      45              :     #[error(transparent)]
      46              :     NotFound(crate::tenant::GetTimelineError),
      47              : 
      48              :     #[error("failed to reparent all candidate timelines, please retry")]
      49              :     FailedToReparentAll,
      50              : 
      51              :     #[error("ancestor is already being detached by: {}", .0)]
      52              :     OtherTimelineDetachOngoing(TimelineId),
      53              : 
      54              :     #[error("preparing to timeline ancestor detach failed")]
      55              :     Prepare(#[source] anyhow::Error),
      56              : 
      57              :     #[error("detaching and reparenting failed")]
      58              :     DetachReparent(#[source] anyhow::Error),
      59              : 
      60              :     #[error("completing ancestor detach failed")]
      61              :     Complete(#[source] anyhow::Error),
      62              : 
      63              :     #[error("failpoint: {}", .0)]
      64              :     Failpoint(&'static str),
      65              : }
      66              : 
      67              : impl Error {
      68              :     /// Try to catch cancellation from within the `anyhow::Error`, or wrap the anyhow as the given
      69              :     /// variant or fancier `or_else`.
      70            0 :     fn launder<F>(e: anyhow::Error, or_else: F) -> Error
      71            0 :     where
      72            0 :         F: Fn(anyhow::Error) -> Error,
      73            0 :     {
      74              :         use remote_storage::TimeoutOrCancel;
      75              : 
      76              :         use crate::tenant::remote_timeline_client::WaitCompletionError;
      77              :         use crate::tenant::upload_queue::NotInitialized;
      78              : 
      79            0 :         if e.is::<NotInitialized>()
      80            0 :             || TimeoutOrCancel::caused_by_cancel(&e)
      81            0 :             || e.downcast_ref::<remote_storage::DownloadError>()
      82            0 :                 .is_some_and(|e| e.is_cancelled())
      83            0 :             || e.is::<WaitCompletionError>()
      84              :         {
      85            0 :             Error::ShuttingDown
      86              :         } else {
      87            0 :             or_else(e)
      88              :         }
      89            0 :     }
      90              : }
      91              : 
      92              : impl From<Error> for ApiError {
      93            0 :     fn from(value: Error) -> Self {
      94            0 :         match value {
      95            0 :             Error::NoAncestor => ApiError::Conflict(value.to_string()),
      96              :             Error::TooManyAncestors | Error::AncestorNotEmpty => {
      97            0 :                 ApiError::BadRequest(anyhow::anyhow!("{value}"))
      98              :             }
      99            0 :             Error::ShuttingDown => ApiError::ShuttingDown,
     100            0 :             Error::Archived(_) => ApiError::BadRequest(anyhow::anyhow!("{value}")),
     101              :             Error::OtherTimelineDetachOngoing(_) | Error::FailedToReparentAll => {
     102            0 :                 ApiError::ResourceUnavailable(value.to_string().into())
     103              :             }
     104            0 :             Error::NotFound(e) => ApiError::from(e),
     105              :             // these variants should have no cancellation errors because of Error::launder
     106              :             Error::Prepare(_)
     107              :             | Error::DetachReparent(_)
     108              :             | Error::Complete(_)
     109            0 :             | Error::Failpoint(_) => ApiError::InternalServerError(value.into()),
     110              :         }
     111            0 :     }
     112              : }
     113              : 
     114              : impl From<crate::tenant::upload_queue::NotInitialized> for Error {
     115            0 :     fn from(_: crate::tenant::upload_queue::NotInitialized) -> Self {
     116            0 :         // treat all as shutting down signals, even though that is not entirely correct
     117            0 :         // (uninitialized state)
     118            0 :         Error::ShuttingDown
     119            0 :     }
     120              : }
     121              : impl From<super::layer_manager::Shutdown> for Error {
     122            0 :     fn from(_: super::layer_manager::Shutdown) -> Self {
     123            0 :         Error::ShuttingDown
     124            0 :     }
     125              : }
     126              : 
     127              : pub(crate) enum Progress {
     128              :     Prepared(Attempt, PreparedTimelineDetach),
     129              :     Done(AncestorDetached),
     130              : }
     131              : 
     132              : pub(crate) struct PreparedTimelineDetach {
     133              :     layers: Vec<Layer>,
     134              : }
     135              : 
     136              : // TODO: this should be part of PageserverConf because we cannot easily modify cplane arguments.
     137              : #[derive(Debug)]
     138              : pub(crate) struct Options {
     139              :     pub(crate) rewrite_concurrency: std::num::NonZeroUsize,
     140              :     pub(crate) copy_concurrency: std::num::NonZeroUsize,
     141              : }
     142              : 
     143              : impl Default for Options {
     144            0 :     fn default() -> Self {
     145            0 :         Self {
     146            0 :             rewrite_concurrency: std::num::NonZeroUsize::new(2).unwrap(),
     147            0 :             copy_concurrency: std::num::NonZeroUsize::new(100).unwrap(),
     148            0 :         }
     149            0 :     }
     150              : }
     151              : 
     152              : /// Represents an across tenant reset exclusive single attempt to detach ancestor.
     153              : #[derive(Debug)]
     154              : pub(crate) struct Attempt {
     155              :     pub(crate) timeline_id: TimelineId,
     156              :     pub(crate) ancestor_timeline_id: TimelineId,
     157              :     pub(crate) ancestor_lsn: Lsn,
     158              :     _guard: completion::Completion,
     159              :     gate_entered: Option<utils::sync::gate::GateGuard>,
     160              : }
     161              : 
     162              : impl Attempt {
     163            0 :     pub(crate) fn before_reset_tenant(&mut self) {
     164            0 :         let taken = self.gate_entered.take();
     165            0 :         assert!(taken.is_some());
     166            0 :     }
     167              : 
     168            0 :     pub(crate) fn new_barrier(&self) -> completion::Barrier {
     169            0 :         self._guard.barrier()
     170            0 :     }
     171              : }
     172              : 
     173              : /// See [`Timeline::prepare_to_detach_from_ancestor`]
     174            0 : pub(super) async fn prepare(
     175            0 :     detached: &Arc<Timeline>,
     176            0 :     tenant: &Tenant,
     177            0 :     behavior: DetachBehavior,
     178            0 :     options: Options,
     179            0 :     ctx: &RequestContext,
     180            0 : ) -> Result<Progress, Error> {
     181              :     use Error::*;
     182              : 
     183            0 :     let Some((mut ancestor, mut ancestor_lsn)) = detached
     184            0 :         .ancestor_timeline
     185            0 :         .as_ref()
     186            0 :         .map(|tl| (tl.clone(), detached.ancestor_lsn))
     187              :     else {
     188              :         let ancestor_id;
     189              :         let ancestor_lsn;
     190            0 :         let still_in_progress = {
     191            0 :             let accessor = detached.remote_client.initialized_upload_queue()?;
     192              : 
     193              :             // we are safe to inspect the latest uploaded, because we can only witness this after
     194              :             // restart is complete and ancestor is no more.
     195            0 :             let latest = accessor.latest_uploaded_index_part();
     196            0 :             let Some((id, lsn)) = latest.lineage.detached_previous_ancestor() else {
     197            0 :                 return Err(NoAncestor);
     198              :             };
     199            0 :             ancestor_id = id;
     200            0 :             ancestor_lsn = lsn;
     201            0 : 
     202            0 :             latest
     203            0 :                 .gc_blocking
     204            0 :                 .as_ref()
     205            0 :                 .is_some_and(|b| b.blocked_by(DetachAncestor))
     206            0 :         };
     207            0 : 
     208            0 :         if still_in_progress {
     209              :             // gc is still blocked, we can still reparent and complete.
     210              :             // we are safe to reparent remaining, because they were locked in in the beginning.
     211            0 :             let attempt =
     212            0 :                 continue_with_blocked_gc(detached, tenant, ancestor_id, ancestor_lsn).await?;
     213              : 
     214              :             // because the ancestor of detached is already set to none, we have published all
     215              :             // of the layers, so we are still "prepared."
     216            0 :             return Ok(Progress::Prepared(
     217            0 :                 attempt,
     218            0 :                 PreparedTimelineDetach { layers: Vec::new() },
     219            0 :             ));
     220            0 :         }
     221              : 
     222            0 :         let reparented_timelines = reparented_direct_children(detached, tenant)?;
     223            0 :         return Ok(Progress::Done(AncestorDetached {
     224            0 :             reparented_timelines,
     225            0 :         }));
     226              :     };
     227              : 
     228            0 :     if detached.is_archived() != Some(false) {
     229            0 :         return Err(Archived(detached.timeline_id));
     230            0 :     }
     231            0 : 
     232            0 :     if !ancestor_lsn.is_valid() {
     233              :         // rare case, probably wouldn't even load
     234            0 :         tracing::error!("ancestor is set, but ancestor_lsn is invalid, this timeline needs fixing");
     235            0 :         return Err(NoAncestor);
     236            0 :     }
     237            0 : 
     238            0 :     check_no_archived_children_of_ancestor(tenant, detached, &ancestor, ancestor_lsn)?;
     239              : 
     240            0 :     if let DetachBehavior::MultiLevelAndNoReparent = behavior {
     241              :         // If the ancestor has an ancestor, we might be able to fast-path detach it if the current ancestor does not have any data written/used by the detaching timeline.
     242            0 :         while let Some(ancestor_of_ancestor) = ancestor.ancestor_timeline.clone() {
     243            0 :             if ancestor_lsn != ancestor.ancestor_lsn {
     244              :                 // non-technical requirement; we could flatten still if ancestor LSN does not match but that needs
     245              :                 // us to copy and cut more layers.
     246            0 :                 return Err(AncestorNotEmpty);
     247            0 :             }
     248            0 :             // Use the ancestor of the ancestor as the new ancestor (only when the ancestor LSNs are the same)
     249            0 :             ancestor_lsn = ancestor.ancestor_lsn; // Get the LSN first before resetting the `ancestor` variable
     250            0 :             ancestor = ancestor_of_ancestor;
     251            0 :             // TODO: do we still need to check if we don't want to reparent?
     252            0 :             check_no_archived_children_of_ancestor(tenant, detached, &ancestor, ancestor_lsn)?;
     253              :         }
     254            0 :     } else if ancestor.ancestor_timeline.is_some() {
     255              :         // non-technical requirement; we could flatten N ancestors just as easily but we chose
     256              :         // not to, at least initially
     257            0 :         return Err(TooManyAncestors);
     258            0 :     }
     259              : 
     260            0 :     tracing::info!(
     261            0 :         "attempt to detach the timeline from the ancestor: {}@{}, behavior={:?}",
     262            0 :         ancestor.timeline_id,
     263              :         ancestor_lsn,
     264              :         behavior
     265              :     );
     266              : 
     267            0 :     let attempt = start_new_attempt(detached, tenant, ancestor.timeline_id, ancestor_lsn).await?;
     268              : 
     269            0 :     utils::pausable_failpoint!("timeline-detach-ancestor::before_starting_after_locking-pausable");
     270              : 
     271            0 :     fail::fail_point!(
     272            0 :         "timeline-detach-ancestor::before_starting_after_locking",
     273            0 :         |_| Err(Error::Failpoint(
     274            0 :             "timeline-detach-ancestor::before_starting_after_locking"
     275            0 :         ))
     276            0 :     );
     277              : 
     278            0 :     if ancestor_lsn >= ancestor.get_disk_consistent_lsn() {
     279            0 :         let span =
     280            0 :             tracing::info_span!("freeze_and_flush", ancestor_timeline_id=%ancestor.timeline_id);
     281            0 :         async {
     282            0 :             let started_at = std::time::Instant::now();
     283            0 :             let freeze_and_flush = ancestor.freeze_and_flush0();
     284            0 :             let mut freeze_and_flush = std::pin::pin!(freeze_and_flush);
     285              : 
     286            0 :             let res =
     287            0 :                 tokio::time::timeout(std::time::Duration::from_secs(1), &mut freeze_and_flush)
     288            0 :                     .await;
     289              : 
     290            0 :             let res = match res {
     291            0 :                 Ok(res) => res,
     292            0 :                 Err(_elapsed) => {
     293            0 :                     tracing::info!("freezing and flushing ancestor is still ongoing");
     294            0 :                     freeze_and_flush.await
     295              :                 }
     296              :             };
     297              : 
     298            0 :             res.map_err(|e| {
     299              :                 use FlushLayerError::*;
     300            0 :                 match e {
     301              :                     Cancelled | NotRunning(_) => {
     302              :                         // FIXME(#6424): technically statically unreachable right now, given how we never
     303              :                         // drop the sender
     304            0 :                         Error::ShuttingDown
     305              :                     }
     306            0 :                     CreateImageLayersError(_) | Other(_) => Error::Prepare(e.into()),
     307              :                 }
     308            0 :             })?;
     309              : 
     310              :             // we do not need to wait for uploads to complete but we do need `struct Layer`,
     311              :             // copying delta prefix is unsupported currently for `InMemoryLayer`.
     312            0 :             tracing::info!(
     313            0 :                 elapsed_ms = started_at.elapsed().as_millis(),
     314            0 :                 "froze and flushed the ancestor"
     315              :             );
     316            0 :             Ok::<_, Error>(())
     317            0 :         }
     318            0 :         .instrument(span)
     319            0 :         .await?;
     320            0 :     }
     321              : 
     322            0 :     let end_lsn = ancestor_lsn + 1;
     323              : 
     324            0 :     let (filtered_layers, straddling_branchpoint, rest_of_historic) = {
     325              :         // we do not need to start from our layers, because they can only be layers that come
     326              :         // *after* ancestor_lsn
     327            0 :         let layers = tokio::select! {
     328            0 :             guard = ancestor.layers.read() => guard,
     329            0 :             _ = detached.cancel.cancelled() => {
     330            0 :                 return Err(ShuttingDown);
     331              :             }
     332            0 :             _ = ancestor.cancel.cancelled() => {
     333            0 :                 return Err(ShuttingDown);
     334              :             }
     335              :         };
     336              : 
     337              :         // between retries, these can change if compaction or gc ran in between. this will mean
     338              :         // we have to redo work.
     339            0 :         partition_work(ancestor_lsn, &layers)?
     340              :     };
     341              : 
     342              :     // TODO: layers are already sorted by something: use that to determine how much of remote
     343              :     // copies are already done -- gc is blocked, but a compaction could had happened on ancestor,
     344              :     // which is something to keep in mind if copy skipping is implemented.
     345            0 :     tracing::info!(filtered=%filtered_layers, to_rewrite = straddling_branchpoint.len(), historic=%rest_of_historic.len(), "collected layers");
     346              : 
     347              :     // TODO: copying and lsn prefix copying could be done at the same time with a single fsync after
     348            0 :     let mut new_layers: Vec<Layer> =
     349            0 :         Vec::with_capacity(straddling_branchpoint.len() + rest_of_historic.len());
     350            0 : 
     351            0 :     {
     352            0 :         tracing::debug!(to_rewrite = %straddling_branchpoint.len(), "copying prefix of delta layers");
     353              : 
     354            0 :         let mut tasks = tokio::task::JoinSet::new();
     355            0 : 
     356            0 :         let mut wrote_any = false;
     357            0 : 
     358            0 :         let limiter = Arc::new(Semaphore::new(options.rewrite_concurrency.get()));
     359              : 
     360            0 :         for layer in straddling_branchpoint {
     361            0 :             let limiter = limiter.clone();
     362            0 :             let timeline = detached.clone();
     363            0 :             let ctx = ctx.detached_child(TaskKind::DetachAncestor, DownloadBehavior::Download);
     364              : 
     365            0 :             let span = tracing::info_span!("upload_rewritten_layer", %layer);
     366            0 :             tasks.spawn(
     367            0 :                 async move {
     368            0 :                     let _permit = limiter.acquire().await;
     369            0 :                     let copied =
     370            0 :                         upload_rewritten_layer(end_lsn, &layer, &timeline, &timeline.cancel, &ctx)
     371            0 :                             .await?;
     372            0 :                     if let Some(copied) = copied.as_ref() {
     373            0 :                         tracing::info!(%copied, "rewrote and uploaded");
     374            0 :                     }
     375            0 :                     Ok(copied)
     376            0 :                 }
     377            0 :                 .instrument(span),
     378            0 :             );
     379            0 :         }
     380              : 
     381            0 :         while let Some(res) = tasks.join_next().await {
     382            0 :             match res {
     383            0 :                 Ok(Ok(Some(copied))) => {
     384            0 :                     wrote_any = true;
     385            0 :                     new_layers.push(copied);
     386            0 :                 }
     387            0 :                 Ok(Ok(None)) => {}
     388            0 :                 Ok(Err(e)) => return Err(e),
     389            0 :                 Err(je) => return Err(Error::Prepare(je.into())),
     390              :             }
     391              :         }
     392              : 
     393              :         // FIXME: the fsync should be mandatory, after both rewrites and copies
     394            0 :         if wrote_any {
     395            0 :             fsync_timeline_dir(detached, ctx).await;
     396            0 :         }
     397              :     }
     398              : 
     399            0 :     let mut tasks = tokio::task::JoinSet::new();
     400            0 :     let limiter = Arc::new(Semaphore::new(options.copy_concurrency.get()));
     401            0 :     let cancel_eval = CancellationToken::new();
     402              : 
     403            0 :     for adopted in rest_of_historic {
     404            0 :         let limiter = limiter.clone();
     405            0 :         let timeline = detached.clone();
     406            0 :         let cancel_eval = cancel_eval.clone();
     407            0 : 
     408            0 :         tasks.spawn(
     409            0 :             async move {
     410            0 :                 let _permit = tokio::select! {
     411            0 :                     permit = limiter.acquire() => {
     412            0 :                         permit
     413              :                     }
     414              :                     // Wait for the cancellation here instead of letting the entire task be cancelled.
     415              :                     // Cancellations are racy in that they might leave layers on disk.
     416            0 :                     _ = cancel_eval.cancelled() => {
     417            0 :                         Err(Error::ShuttingDown)?
     418              :                     }
     419              :                 };
     420            0 :                 let (owned, did_hardlink) = remote_copy(
     421            0 :                     &adopted,
     422            0 :                     &timeline,
     423            0 :                     timeline.generation,
     424            0 :                     timeline.shard_identity,
     425            0 :                     &timeline.cancel,
     426            0 :                 )
     427            0 :                 .await?;
     428            0 :                 tracing::info!(layer=%owned, did_hard_link=%did_hardlink, "remote copied");
     429            0 :                 Ok((owned, did_hardlink))
     430            0 :             }
     431            0 :             .in_current_span(),
     432            0 :         );
     433            0 :     }
     434              : 
     435            0 :     fn delete_layers(timeline: &Timeline, layers: Vec<Layer>) -> Result<(), Error> {
     436              :         // We are deleting layers, so we must hold the gate
     437            0 :         let _gate = timeline.gate.enter().map_err(|e| match e {
     438            0 :             GateError::GateClosed => Error::ShuttingDown,
     439            0 :         })?;
     440            0 :         {
     441            0 :             layers.into_iter().for_each(|l: Layer| {
     442            0 :                 l.delete_on_drop();
     443            0 :                 std::mem::drop(l);
     444            0 :             });
     445            0 :         }
     446            0 :         Ok(())
     447            0 :     }
     448              : 
     449            0 :     let mut should_fsync = false;
     450            0 :     let mut first_err = None;
     451            0 :     while let Some(res) = tasks.join_next().await {
     452            0 :         match res {
     453            0 :             Ok(Ok((owned, did_hardlink))) => {
     454            0 :                 if did_hardlink {
     455            0 :                     should_fsync = true;
     456            0 :                 }
     457            0 :                 new_layers.push(owned);
     458              :             }
     459              : 
     460              :             // Don't stop the evaluation on errors, so that we get the full set of hardlinked layers to delete.
     461            0 :             Ok(Err(failed)) => {
     462            0 :                 cancel_eval.cancel();
     463            0 :                 first_err.get_or_insert(failed);
     464            0 :             }
     465            0 :             Err(je) => {
     466            0 :                 cancel_eval.cancel();
     467            0 :                 first_err.get_or_insert(Error::Prepare(je.into()));
     468            0 :             }
     469              :         }
     470              :     }
     471              : 
     472            0 :     if let Some(failed) = first_err {
     473            0 :         delete_layers(detached, new_layers)?;
     474            0 :         return Err(failed);
     475            0 :     }
     476            0 : 
     477            0 :     // fsync directory again if we hardlinked something
     478            0 :     if should_fsync {
     479            0 :         fsync_timeline_dir(detached, ctx).await;
     480            0 :     }
     481              : 
     482            0 :     let prepared = PreparedTimelineDetach { layers: new_layers };
     483            0 : 
     484            0 :     Ok(Progress::Prepared(attempt, prepared))
     485            0 : }
     486              : 
     487            0 : async fn start_new_attempt(
     488            0 :     detached: &Timeline,
     489            0 :     tenant: &Tenant,
     490            0 :     ancestor_timeline_id: TimelineId,
     491            0 :     ancestor_lsn: Lsn,
     492            0 : ) -> Result<Attempt, Error> {
     493            0 :     let attempt = obtain_exclusive_attempt(detached, tenant, ancestor_timeline_id, ancestor_lsn)?;
     494              : 
     495              :     // insert the block in the index_part.json, if not already there.
     496            0 :     let _dont_care = tenant
     497            0 :         .gc_block
     498            0 :         .insert(
     499            0 :             detached,
     500            0 :             crate::tenant::remote_timeline_client::index::GcBlockingReason::DetachAncestor,
     501            0 :         )
     502            0 :         .await
     503            0 :         .map_err(|e| Error::launder(e, Error::Prepare))?;
     504              : 
     505            0 :     Ok(attempt)
     506            0 : }
     507              : 
     508            0 : async fn continue_with_blocked_gc(
     509            0 :     detached: &Timeline,
     510            0 :     tenant: &Tenant,
     511            0 :     ancestor_timeline_id: TimelineId,
     512            0 :     ancestor_lsn: Lsn,
     513            0 : ) -> Result<Attempt, Error> {
     514            0 :     // FIXME: it would be nice to confirm that there is an in-memory version, since we've just
     515            0 :     // verified there is a persistent one?
     516            0 :     obtain_exclusive_attempt(detached, tenant, ancestor_timeline_id, ancestor_lsn)
     517            0 : }
     518              : 
     519            0 : fn obtain_exclusive_attempt(
     520            0 :     detached: &Timeline,
     521            0 :     tenant: &Tenant,
     522            0 :     ancestor_timeline_id: TimelineId,
     523            0 :     ancestor_lsn: Lsn,
     524            0 : ) -> Result<Attempt, Error> {
     525              :     use Error::{OtherTimelineDetachOngoing, ShuttingDown};
     526              : 
     527              :     // ensure we are the only active attempt for this tenant
     528            0 :     let (guard, barrier) = completion::channel();
     529            0 :     {
     530            0 :         let mut guard = tenant.ongoing_timeline_detach.lock().unwrap();
     531            0 :         if let Some((tl, other)) = guard.as_ref() {
     532            0 :             if !other.is_ready() {
     533            0 :                 return Err(OtherTimelineDetachOngoing(*tl));
     534            0 :             }
     535              :             // FIXME: no test enters here
     536            0 :         }
     537            0 :         *guard = Some((detached.timeline_id, barrier));
     538              :     }
     539              : 
     540              :     // ensure the gate is still open
     541            0 :     let _gate_entered = detached.gate.enter().map_err(|_| ShuttingDown)?;
     542              : 
     543            0 :     Ok(Attempt {
     544            0 :         timeline_id: detached.timeline_id,
     545            0 :         ancestor_timeline_id,
     546            0 :         ancestor_lsn,
     547            0 :         _guard: guard,
     548            0 :         gate_entered: Some(_gate_entered),
     549            0 :     })
     550            0 : }
     551              : 
     552            0 : fn reparented_direct_children(
     553            0 :     detached: &Arc<Timeline>,
     554            0 :     tenant: &Tenant,
     555            0 : ) -> Result<HashSet<TimelineId>, Error> {
     556            0 :     let mut all_direct_children = tenant
     557            0 :         .timelines
     558            0 :         .lock()
     559            0 :         .unwrap()
     560            0 :         .values()
     561            0 :         .filter_map(|tl| {
     562            0 :             let is_direct_child = matches!(tl.ancestor_timeline.as_ref(), Some(ancestor) if Arc::ptr_eq(ancestor, detached));
     563              : 
     564            0 :             if is_direct_child {
     565            0 :                 Some(tl.clone())
     566              :             } else {
     567            0 :                 if let Some(timeline) = tl.ancestor_timeline.as_ref() {
     568            0 :                     assert_ne!(timeline.timeline_id, detached.timeline_id, "we cannot have two timelines with the same timeline_id live");
     569            0 :                 }
     570            0 :                 None
     571              :             }
     572            0 :         })
     573            0 :         // Collect to avoid lock taking order problem with Tenant::timelines and
     574            0 :         // Timeline::remote_client
     575            0 :         .collect::<Vec<_>>();
     576            0 : 
     577            0 :     let mut any_shutdown = false;
     578            0 : 
     579            0 :     all_direct_children.retain(|tl| match tl.remote_client.initialized_upload_queue() {
     580            0 :         Ok(accessor) => accessor
     581            0 :             .latest_uploaded_index_part()
     582            0 :             .lineage
     583            0 :             .is_reparented(),
     584            0 :         Err(_shutdownalike) => {
     585            0 :             // not 100% a shutdown, but let's bail early not to give inconsistent results in
     586            0 :             // sharded enviroment.
     587            0 :             any_shutdown = true;
     588            0 :             true
     589              :         }
     590            0 :     });
     591            0 : 
     592            0 :     if any_shutdown {
     593              :         // it could be one or many being deleted; have client retry
     594            0 :         return Err(Error::ShuttingDown);
     595            0 :     }
     596            0 : 
     597            0 :     Ok(all_direct_children
     598            0 :         .into_iter()
     599            0 :         .map(|tl| tl.timeline_id)
     600            0 :         .collect())
     601            0 : }
     602              : 
     603            0 : fn partition_work(
     604            0 :     ancestor_lsn: Lsn,
     605            0 :     source: &LayerManager,
     606            0 : ) -> Result<(usize, Vec<Layer>, Vec<Layer>), Error> {
     607            0 :     let mut straddling_branchpoint = vec![];
     608            0 :     let mut rest_of_historic = vec![];
     609            0 : 
     610            0 :     let mut later_by_lsn = 0;
     611              : 
     612            0 :     for desc in source.layer_map()?.iter_historic_layers() {
     613              :         // off by one chances here:
     614              :         // - start is inclusive
     615              :         // - end is exclusive
     616            0 :         if desc.lsn_range.start > ancestor_lsn {
     617            0 :             later_by_lsn += 1;
     618            0 :             continue;
     619            0 :         }
     620              : 
     621            0 :         let target = if desc.lsn_range.start <= ancestor_lsn
     622            0 :             && desc.lsn_range.end > ancestor_lsn
     623            0 :             && desc.is_delta
     624              :         {
     625              :             // TODO: image layer at Lsn optimization
     626            0 :             &mut straddling_branchpoint
     627              :         } else {
     628            0 :             &mut rest_of_historic
     629              :         };
     630              : 
     631            0 :         target.push(source.get_from_desc(&desc));
     632              :     }
     633              : 
     634            0 :     Ok((later_by_lsn, straddling_branchpoint, rest_of_historic))
     635            0 : }
     636              : 
     637            0 : async fn upload_rewritten_layer(
     638            0 :     end_lsn: Lsn,
     639            0 :     layer: &Layer,
     640            0 :     target: &Arc<Timeline>,
     641            0 :     cancel: &CancellationToken,
     642            0 :     ctx: &RequestContext,
     643            0 : ) -> Result<Option<Layer>, Error> {
     644            0 :     let copied = copy_lsn_prefix(end_lsn, layer, target, ctx).await?;
     645              : 
     646            0 :     let Some(copied) = copied else {
     647            0 :         return Ok(None);
     648              :     };
     649              : 
     650            0 :     target
     651            0 :         .remote_client
     652            0 :         .upload_layer_file(&copied, cancel)
     653            0 :         .await
     654            0 :         .map_err(|e| Error::launder(e, Error::Prepare))?;
     655              : 
     656            0 :     Ok(Some(copied.into()))
     657            0 : }
     658              : 
     659            0 : async fn copy_lsn_prefix(
     660            0 :     end_lsn: Lsn,
     661            0 :     layer: &Layer,
     662            0 :     target_timeline: &Arc<Timeline>,
     663            0 :     ctx: &RequestContext,
     664            0 : ) -> Result<Option<ResidentLayer>, Error> {
     665            0 :     if target_timeline.cancel.is_cancelled() {
     666            0 :         return Err(Error::ShuttingDown);
     667            0 :     }
     668            0 : 
     669            0 :     tracing::debug!(%layer, %end_lsn, "copying lsn prefix");
     670              : 
     671            0 :     let mut writer = DeltaLayerWriter::new(
     672            0 :         target_timeline.conf,
     673            0 :         target_timeline.timeline_id,
     674            0 :         target_timeline.tenant_shard_id,
     675            0 :         layer.layer_desc().key_range.start,
     676            0 :         layer.layer_desc().lsn_range.start..end_lsn,
     677            0 :         ctx,
     678            0 :     )
     679            0 :     .await
     680            0 :     .with_context(|| format!("prepare to copy lsn prefix of ancestors {layer}"))
     681            0 :     .map_err(Error::Prepare)?;
     682              : 
     683            0 :     let resident = layer.download_and_keep_resident(ctx).await.map_err(|e| {
     684            0 :         if e.is_cancelled() {
     685            0 :             Error::ShuttingDown
     686              :         } else {
     687            0 :             Error::Prepare(e.into())
     688              :         }
     689            0 :     })?;
     690              : 
     691            0 :     let records = resident
     692            0 :         .copy_delta_prefix(&mut writer, end_lsn, ctx)
     693            0 :         .await
     694            0 :         .with_context(|| format!("copy lsn prefix of ancestors {layer}"))
     695            0 :         .map_err(Error::Prepare)?;
     696              : 
     697            0 :     drop(resident);
     698            0 : 
     699            0 :     tracing::debug!(%layer, records, "copied records");
     700              : 
     701            0 :     if records == 0 {
     702            0 :         drop(writer);
     703            0 :         // TODO: we might want to store an empty marker in remote storage for this
     704            0 :         // layer so that we will not needlessly walk `layer` on repeated attempts.
     705            0 :         Ok(None)
     706              :     } else {
     707              :         // reuse the key instead of adding more holes between layers by using the real
     708              :         // highest key in the layer.
     709            0 :         let reused_highest_key = layer.layer_desc().key_range.end;
     710            0 :         let (desc, path) = writer
     711            0 :             .finish(reused_highest_key, ctx)
     712            0 :             .await
     713            0 :             .map_err(Error::Prepare)?;
     714            0 :         let copied = Layer::finish_creating(target_timeline.conf, target_timeline, desc, &path)
     715            0 :             .map_err(Error::Prepare)?;
     716              : 
     717            0 :         tracing::debug!(%layer, %copied, "new layer produced");
     718              : 
     719            0 :         Ok(Some(copied))
     720              :     }
     721            0 : }
     722              : 
     723              : /// Creates a new Layer instance for the adopted layer, and ensures it is found in the remote
     724              : /// storage on successful return. without the adopted layer being added to `index_part.json`.
     725              : /// Returns (Layer, did hardlink)
     726            0 : async fn remote_copy(
     727            0 :     adopted: &Layer,
     728            0 :     adoptee: &Arc<Timeline>,
     729            0 :     generation: Generation,
     730            0 :     shard_identity: ShardIdentity,
     731            0 :     cancel: &CancellationToken,
     732            0 : ) -> Result<(Layer, bool), Error> {
     733            0 :     let mut metadata = adopted.metadata();
     734            0 :     debug_assert!(metadata.generation <= generation);
     735            0 :     metadata.generation = generation;
     736            0 :     metadata.shard = shard_identity.shard_index();
     737            0 : 
     738            0 :     let conf = adoptee.conf;
     739            0 :     let file_name = adopted.layer_desc().layer_name();
     740              : 
     741              :     // We don't want to shut the timeline down during this operation because we do `delete_on_drop` below
     742            0 :     let _gate = adoptee.gate.enter().map_err(|e| match e {
     743            0 :         GateError::GateClosed => Error::ShuttingDown,
     744            0 :     })?;
     745              : 
     746              :     // depending if Layer::keep_resident, do a hardlink
     747              :     let did_hardlink;
     748            0 :     let owned = if let Some(adopted_resident) = adopted.keep_resident().await {
     749            0 :         let adopted_path = adopted_resident.local_path();
     750            0 :         let adoptee_path = local_layer_path(
     751            0 :             conf,
     752            0 :             &adoptee.tenant_shard_id,
     753            0 :             &adoptee.timeline_id,
     754            0 :             &file_name,
     755            0 :             &metadata.generation,
     756            0 :         );
     757            0 : 
     758            0 :         match std::fs::hard_link(adopted_path, &adoptee_path) {
     759            0 :             Ok(()) => {}
     760            0 :             Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
     761            0 :                 // In theory we should not get into this situation as we are doing cleanups of the layer file after errors.
     762            0 :                 // However, we don't do cleanups for errors past `prepare`, so there is the slight chance to get to this branch.
     763            0 : 
     764            0 :                 // Double check that the file is orphan (probably from an earlier attempt), then delete it
     765            0 :                 let key = file_name.clone().into();
     766            0 :                 if adoptee.layers.read().await.contains_key(&key) {
     767              :                     // We are supposed to filter out such cases before coming to this function
     768            0 :                     return Err(Error::Prepare(anyhow::anyhow!(
     769            0 :                         "layer file {file_name} already present and inside layer map"
     770            0 :                     )));
     771            0 :                 }
     772            0 :                 tracing::info!("Deleting orphan layer file to make way for hard linking");
     773              :                 // Delete orphan layer file and try again, to ensure this layer has a well understood source
     774            0 :                 std::fs::remove_file(adopted_path)
     775            0 :                     .map_err(|e| Error::launder(e.into(), Error::Prepare))?;
     776            0 :                 std::fs::hard_link(adopted_path, &adoptee_path)
     777            0 :                     .map_err(|e| Error::launder(e.into(), Error::Prepare))?;
     778              :             }
     779            0 :             Err(e) => {
     780            0 :                 return Err(Error::launder(e.into(), Error::Prepare));
     781              :             }
     782              :         };
     783            0 :         did_hardlink = true;
     784            0 :         Layer::for_resident(conf, adoptee, adoptee_path, file_name, metadata).drop_eviction_guard()
     785              :     } else {
     786            0 :         did_hardlink = false;
     787            0 :         Layer::for_evicted(conf, adoptee, file_name, metadata)
     788              :     };
     789              : 
     790            0 :     let layer = match adoptee
     791            0 :         .remote_client
     792            0 :         .copy_timeline_layer(adopted, &owned, cancel)
     793            0 :         .await
     794              :     {
     795            0 :         Ok(()) => owned,
     796            0 :         Err(e) => {
     797            0 :             {
     798            0 :                 // Clean up the layer so that on a retry we don't get errors that the file already exists
     799            0 :                 owned.delete_on_drop();
     800            0 :                 std::mem::drop(owned);
     801            0 :             }
     802            0 :             return Err(Error::launder(e, Error::Prepare));
     803              :         }
     804              :     };
     805              : 
     806            0 :     Ok((layer, did_hardlink))
     807            0 : }
     808              : 
     809              : pub(crate) enum DetachingAndReparenting {
     810              :     /// All of the following timeline ids were reparented and the timeline ancestor detach must be
     811              :     /// marked as completed.
     812              :     Reparented(HashSet<TimelineId>),
     813              : 
     814              :     /// Some of the reparentings failed. The timeline ancestor detach must **not** be marked as
     815              :     /// completed.
     816              :     ///
     817              :     /// Nested `must_reset_tenant` is set to true when any restart requiring changes were made.
     818              :     SomeReparentingFailed { must_reset_tenant: bool },
     819              : 
     820              :     /// Detaching and reparentings were completed in a previous attempt. Timeline ancestor detach
     821              :     /// must be marked as completed.
     822              :     AlreadyDone(HashSet<TimelineId>),
     823              : }
     824              : 
     825              : impl DetachingAndReparenting {
     826            0 :     pub(crate) fn reset_tenant_required(&self) -> bool {
     827              :         use DetachingAndReparenting::*;
     828            0 :         match self {
     829            0 :             Reparented(_) => true,
     830            0 :             SomeReparentingFailed { must_reset_tenant } => *must_reset_tenant,
     831            0 :             AlreadyDone(_) => false,
     832              :         }
     833            0 :     }
     834              : 
     835            0 :     pub(crate) fn completed(self) -> Option<HashSet<TimelineId>> {
     836              :         use DetachingAndReparenting::*;
     837            0 :         match self {
     838            0 :             Reparented(x) | AlreadyDone(x) => Some(x),
     839            0 :             SomeReparentingFailed { .. } => None,
     840              :         }
     841            0 :     }
     842              : }
     843              : 
     844              : /// See [`Timeline::detach_from_ancestor_and_reparent`].
     845            0 : pub(super) async fn detach_and_reparent(
     846            0 :     detached: &Arc<Timeline>,
     847            0 :     tenant: &Tenant,
     848            0 :     prepared: PreparedTimelineDetach,
     849            0 :     ancestor_timeline_id: TimelineId,
     850            0 :     ancestor_lsn: Lsn,
     851            0 :     behavior: DetachBehavior,
     852            0 :     _ctx: &RequestContext,
     853            0 : ) -> Result<DetachingAndReparenting, Error> {
     854            0 :     let PreparedTimelineDetach { layers } = prepared;
     855              : 
     856              :     #[derive(Debug)]
     857              :     enum Ancestor {
     858              :         NotDetached(Arc<Timeline>, Lsn),
     859              :         Detached(Arc<Timeline>, Lsn),
     860              :     }
     861              : 
     862            0 :     let (recorded_branchpoint, still_ongoing) = {
     863            0 :         let access = detached.remote_client.initialized_upload_queue()?;
     864            0 :         let latest = access.latest_uploaded_index_part();
     865            0 : 
     866            0 :         (
     867            0 :             latest.lineage.detached_previous_ancestor(),
     868            0 :             latest
     869            0 :                 .gc_blocking
     870            0 :                 .as_ref()
     871            0 :                 .is_some_and(|b| b.blocked_by(DetachAncestor)),
     872            0 :         )
     873            0 :     };
     874            0 :     assert!(
     875            0 :         still_ongoing,
     876            0 :         "cannot (detach? reparent)? complete if the operation is not still ongoing"
     877              :     );
     878              : 
     879            0 :     let ancestor_to_detach = match detached.ancestor_timeline.as_ref() {
     880            0 :         Some(mut ancestor) => {
     881            0 :             while ancestor.timeline_id != ancestor_timeline_id {
     882            0 :                 match ancestor.ancestor_timeline.as_ref() {
     883            0 :                     Some(found) => {
     884            0 :                         if ancestor_lsn != ancestor.ancestor_lsn {
     885            0 :                             return Err(Error::DetachReparent(anyhow::anyhow!(
     886            0 :                                 "cannot find the ancestor timeline to detach from: wrong ancestor lsn"
     887            0 :                             )));
     888            0 :                         }
     889            0 :                         ancestor = found;
     890              :                     }
     891              :                     None => {
     892            0 :                         return Err(Error::DetachReparent(anyhow::anyhow!(
     893            0 :                             "cannot find the ancestor timeline to detach from"
     894            0 :                         )));
     895              :                     }
     896              :                 }
     897              :             }
     898            0 :             Some(ancestor)
     899              :         }
     900            0 :         None => None,
     901              :     };
     902            0 :     let ancestor = match (ancestor_to_detach, recorded_branchpoint) {
     903            0 :         (Some(ancestor), None) => {
     904            0 :             assert!(
     905            0 :                 !layers.is_empty(),
     906            0 :                 "there should always be at least one layer to inherit"
     907              :             );
     908            0 :             Ancestor::NotDetached(ancestor.clone(), detached.ancestor_lsn)
     909              :         }
     910              :         (Some(_), Some(_)) => {
     911            0 :             panic!(
     912            0 :                 "it should be impossible to get to here without having gone through the tenant reset; if the tenant was reset, then the ancestor_timeline would be None"
     913            0 :             );
     914              :         }
     915            0 :         (None, Some((ancestor_id, ancestor_lsn))) => {
     916            0 :             // it has been either:
     917            0 :             // - detached but still exists => we can try reparenting
     918            0 :             // - detached and deleted
     919            0 :             //
     920            0 :             // either way, we must complete
     921            0 :             assert!(
     922            0 :                 layers.is_empty(),
     923            0 :                 "no layers should had been copied as detach is done"
     924              :             );
     925              : 
     926            0 :             let existing = tenant.timelines.lock().unwrap().get(&ancestor_id).cloned();
     927              : 
     928            0 :             if let Some(ancestor) = existing {
     929            0 :                 Ancestor::Detached(ancestor, ancestor_lsn)
     930              :             } else {
     931            0 :                 let direct_children = reparented_direct_children(detached, tenant)?;
     932            0 :                 return Ok(DetachingAndReparenting::AlreadyDone(direct_children));
     933              :             }
     934              :         }
     935              :         (None, None) => {
     936              :             // TODO: make sure there are no `?` before tenant_reset from after a questionmark from
     937              :             // here.
     938            0 :             panic!(
     939            0 :                 "bug: detach_and_reparent called on a timeline which has not been detached or which has no live ancestor"
     940            0 :             );
     941              :         }
     942              :     };
     943              : 
     944              :     // publish the prepared layers before we reparent any of the timelines, so that on restart
     945              :     // reparented timelines find layers. also do the actual detaching.
     946              :     //
     947              :     // if we crash after this operation, a retry will allow reparenting the remaining timelines as
     948              :     // gc is blocked.
     949              : 
     950            0 :     let (ancestor, ancestor_lsn, was_detached) = match ancestor {
     951            0 :         Ancestor::NotDetached(ancestor, ancestor_lsn) => {
     952            0 :             // this has to complete before any reparentings because otherwise they would not have
     953            0 :             // layers on the new parent.
     954            0 :             detached
     955            0 :                 .remote_client
     956            0 :                 .schedule_adding_existing_layers_to_index_detach_and_wait(
     957            0 :                     &layers,
     958            0 :                     (ancestor.timeline_id, ancestor_lsn),
     959            0 :                 )
     960            0 :                 .await
     961            0 :                 .context("publish layers and detach ancestor")
     962            0 :                 .map_err(|e| Error::launder(e, Error::DetachReparent))?;
     963              : 
     964            0 :             tracing::info!(
     965            0 :                 ancestor=%ancestor.timeline_id,
     966            0 :                 %ancestor_lsn,
     967            0 :                 inherited_layers=%layers.len(),
     968            0 :                 "detached from ancestor"
     969              :             );
     970            0 :             (ancestor, ancestor_lsn, true)
     971              :         }
     972            0 :         Ancestor::Detached(ancestor, ancestor_lsn) => (ancestor, ancestor_lsn, false),
     973              :     };
     974              : 
     975            0 :     if let DetachBehavior::MultiLevelAndNoReparent = behavior {
     976              :         // Do not reparent if the user requests to behave so.
     977            0 :         return Ok(DetachingAndReparenting::Reparented(HashSet::new()));
     978            0 :     }
     979            0 : 
     980            0 :     let mut tasks = tokio::task::JoinSet::new();
     981            0 : 
     982            0 :     // Returns a single permit semaphore which will be used to make one reparenting succeed,
     983            0 :     // others will fail as if those timelines had been stopped for whatever reason.
     984            0 :     #[cfg(feature = "testing")]
     985            0 :     let failpoint_sem = || -> Option<Arc<Semaphore>> {
     986            0 :         fail::fail_point!("timeline-detach-ancestor::allow_one_reparented", |_| Some(
     987            0 :             Arc::new(Semaphore::new(1))
     988            0 :         ));
     989            0 :         None
     990            0 :     }();
     991            0 : 
     992            0 :     // because we are now keeping the slot in progress, it is unlikely that there will be any
     993            0 :     // timeline deletions during this time. if we raced one, then we'll just ignore it.
     994            0 :     {
     995            0 :         let g = tenant.timelines.lock().unwrap();
     996            0 :         reparentable_timelines(g.values(), detached, &ancestor, ancestor_lsn)
     997            0 :             .cloned()
     998            0 :             .for_each(|timeline| {
     999              :                 // important in this scope: we are holding the Tenant::timelines lock
    1000            0 :                 let span = tracing::info_span!("reparent", reparented=%timeline.timeline_id);
    1001            0 :                 let new_parent = detached.timeline_id;
    1002            0 :                 #[cfg(feature = "testing")]
    1003            0 :                 let failpoint_sem = failpoint_sem.clone();
    1004            0 : 
    1005            0 :                 tasks.spawn(
    1006            0 :                     async move {
    1007            0 :                         let res = async {
    1008              :                             #[cfg(feature = "testing")]
    1009            0 :                             if let Some(failpoint_sem) = failpoint_sem {
    1010            0 :                                 let _permit = failpoint_sem.acquire().await.map_err(|_| {
    1011            0 :                                     anyhow::anyhow!(
    1012            0 :                                         "failpoint: timeline-detach-ancestor::allow_one_reparented",
    1013            0 :                                     )
    1014            0 :                                 })?;
    1015            0 :                                 failpoint_sem.close();
    1016            0 :                             }
    1017              : 
    1018            0 :                             timeline
    1019            0 :                                 .remote_client
    1020            0 :                                 .schedule_reparenting_and_wait(&new_parent)
    1021            0 :                                 .await
    1022            0 :                         }
    1023            0 :                         .await;
    1024              : 
    1025            0 :                         match res {
    1026              :                             Ok(()) => {
    1027            0 :                                 tracing::info!("reparented");
    1028            0 :                                 Some(timeline)
    1029              :                             }
    1030            0 :                             Err(e) => {
    1031            0 :                                 // with the use of tenant slot, raced timeline deletion is the most
    1032            0 :                                 // likely reason.
    1033            0 :                                 tracing::warn!("reparenting failed: {e:#}");
    1034            0 :                                 None
    1035              :                             }
    1036              :                         }
    1037            0 :                     }
    1038            0 :                     .instrument(span),
    1039            0 :                 );
    1040            0 :             });
    1041            0 :     }
    1042            0 : 
    1043            0 :     let reparenting_candidates = tasks.len();
    1044            0 :     let mut reparented = HashSet::with_capacity(tasks.len());
    1045              : 
    1046            0 :     while let Some(res) = tasks.join_next().await {
    1047            0 :         match res {
    1048            0 :             Ok(Some(timeline)) => {
    1049            0 :                 assert!(
    1050            0 :                     reparented.insert(timeline.timeline_id),
    1051            0 :                     "duplicate reparenting? timeline_id={}",
    1052            0 :                     timeline.timeline_id
    1053              :                 );
    1054              :             }
    1055            0 :             Err(je) if je.is_cancelled() => unreachable!("not used"),
    1056              :             // just ignore failures now, we can retry
    1057            0 :             Ok(None) => {}
    1058            0 :             Err(je) if je.is_panic() => {}
    1059            0 :             Err(je) => tracing::error!("unexpected join error: {je:?}"),
    1060              :         }
    1061              :     }
    1062              : 
    1063            0 :     let reparented_all = reparenting_candidates == reparented.len();
    1064            0 : 
    1065            0 :     if reparented_all {
    1066            0 :         Ok(DetachingAndReparenting::Reparented(reparented))
    1067              :     } else {
    1068            0 :         tracing::info!(
    1069            0 :             reparented = reparented.len(),
    1070            0 :             candidates = reparenting_candidates,
    1071            0 :             "failed to reparent all candidates; they can be retried after the tenant_reset",
    1072              :         );
    1073              : 
    1074            0 :         let must_reset_tenant = !reparented.is_empty() || was_detached;
    1075            0 :         Ok(DetachingAndReparenting::SomeReparentingFailed { must_reset_tenant })
    1076              :     }
    1077            0 : }
    1078              : 
    1079            0 : pub(super) async fn complete(
    1080            0 :     detached: &Arc<Timeline>,
    1081            0 :     tenant: &Tenant,
    1082            0 :     mut attempt: Attempt,
    1083            0 :     _ctx: &RequestContext,
    1084            0 : ) -> Result<(), Error> {
    1085            0 :     assert_eq!(detached.timeline_id, attempt.timeline_id);
    1086              : 
    1087            0 :     if attempt.gate_entered.is_none() {
    1088            0 :         let entered = detached.gate.enter().map_err(|_| Error::ShuttingDown)?;
    1089            0 :         attempt.gate_entered = Some(entered);
    1090            0 :     } else {
    1091            0 :         // Some(gate_entered) means the tenant was not restarted, as is not required
    1092            0 :     }
    1093              : 
    1094            0 :     assert!(detached.ancestor_timeline.is_none());
    1095              : 
    1096              :     // this should be an 503 at least...?
    1097            0 :     fail::fail_point!(
    1098            0 :         "timeline-detach-ancestor::complete_before_uploading",
    1099            0 :         |_| Err(Error::Failpoint(
    1100            0 :             "timeline-detach-ancestor::complete_before_uploading"
    1101            0 :         ))
    1102            0 :     );
    1103              : 
    1104            0 :     tenant
    1105            0 :         .gc_block
    1106            0 :         .remove(
    1107            0 :             detached,
    1108            0 :             crate::tenant::remote_timeline_client::index::GcBlockingReason::DetachAncestor,
    1109            0 :         )
    1110            0 :         .await
    1111            0 :         .map_err(|e| Error::launder(e, Error::Complete))?;
    1112              : 
    1113            0 :     Ok(())
    1114            0 : }
    1115              : 
    1116              : /// Query against a locked `Tenant::timelines`.
    1117              : ///
    1118              : /// A timeline is reparentable if:
    1119              : ///
    1120              : /// - It is not the timeline being detached.
    1121              : /// - It has the same ancestor as the timeline being detached. Note that the ancestor might not be the direct ancestor.
    1122            0 : fn reparentable_timelines<'a, I>(
    1123            0 :     timelines: I,
    1124            0 :     detached: &'a Arc<Timeline>,
    1125            0 :     ancestor: &'a Arc<Timeline>,
    1126            0 :     ancestor_lsn: Lsn,
    1127            0 : ) -> impl Iterator<Item = &'a Arc<Timeline>> + 'a
    1128            0 : where
    1129            0 :     I: Iterator<Item = &'a Arc<Timeline>> + 'a,
    1130            0 : {
    1131            0 :     timelines.filter_map(move |tl| {
    1132            0 :         if Arc::ptr_eq(tl, detached) {
    1133            0 :             return None;
    1134            0 :         }
    1135              : 
    1136            0 :         let tl_ancestor = tl.ancestor_timeline.as_ref()?;
    1137            0 :         let is_same = Arc::ptr_eq(ancestor, tl_ancestor);
    1138            0 :         let is_earlier = tl.get_ancestor_lsn() <= ancestor_lsn;
    1139            0 : 
    1140            0 :         let is_deleting = tl
    1141            0 :             .delete_progress
    1142            0 :             .try_lock()
    1143            0 :             .map(|flow| !flow.is_not_started())
    1144            0 :             .unwrap_or(true);
    1145            0 : 
    1146            0 :         if is_same && is_earlier && !is_deleting {
    1147            0 :             Some(tl)
    1148              :         } else {
    1149            0 :             None
    1150              :         }
    1151            0 :     })
    1152            0 : }
    1153              : 
    1154            0 : fn check_no_archived_children_of_ancestor(
    1155            0 :     tenant: &Tenant,
    1156            0 :     detached: &Arc<Timeline>,
    1157            0 :     ancestor: &Arc<Timeline>,
    1158            0 :     ancestor_lsn: Lsn,
    1159            0 : ) -> Result<(), Error> {
    1160            0 :     let timelines = tenant.timelines.lock().unwrap();
    1161            0 :     let timelines_offloaded = tenant.timelines_offloaded.lock().unwrap();
    1162            0 :     for timeline in reparentable_timelines(timelines.values(), detached, ancestor, ancestor_lsn) {
    1163            0 :         if timeline.is_archived() == Some(true) {
    1164            0 :             return Err(Error::Archived(timeline.timeline_id));
    1165            0 :         }
    1166              :     }
    1167            0 :     for timeline_offloaded in timelines_offloaded.values() {
    1168            0 :         if timeline_offloaded.ancestor_timeline_id != Some(ancestor.timeline_id) {
    1169            0 :             continue;
    1170            0 :         }
    1171              :         // This forbids the detach ancestor feature if flattened timelines are present,
    1172              :         // even if the ancestor_lsn is from after the branchpoint of the detached timeline.
    1173              :         // But as per current design, we don't record the ancestor_lsn of flattened timelines.
    1174              :         // This is a bit unfortunate, but as of writing this we don't support flattening
    1175              :         // anyway. Maybe we can evolve the data model in the future.
    1176            0 :         if let Some(retain_lsn) = timeline_offloaded.ancestor_retain_lsn {
    1177            0 :             let is_earlier = retain_lsn <= ancestor_lsn;
    1178            0 :             if !is_earlier {
    1179            0 :                 continue;
    1180            0 :             }
    1181            0 :         }
    1182            0 :         return Err(Error::Archived(timeline_offloaded.timeline_id));
    1183              :     }
    1184            0 :     Ok(())
    1185            0 : }
    1186              : 
    1187            0 : async fn fsync_timeline_dir(timeline: &Timeline, ctx: &RequestContext) {
    1188            0 :     let path = &timeline
    1189            0 :         .conf
    1190            0 :         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id);
    1191            0 :     let timeline_dir = VirtualFile::open(&path, ctx)
    1192            0 :         .await
    1193            0 :         .fatal_err("VirtualFile::open for timeline dir fsync");
    1194            0 :     timeline_dir
    1195            0 :         .sync_all()
    1196            0 :         .await
    1197            0 :         .fatal_err("VirtualFile::sync_all timeline dir");
    1198            0 : }
        

Generated by: LCOV version 2.1-beta