LCOV - code coverage report
Current view: top level - pageserver/src/tenant/timeline - detach_ancestor.rs (source / functions) Coverage Total Hit
Test: 553e39c2773e5840c720c90d86e56f89a4330d43.info Lines: 0.0 % 882 0
Test Date: 2025-06-13 20:01:21 Functions: 0.0 % 80 0

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

Generated by: LCOV version 2.1-beta