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