Line data Source code
1 : use std::{
2 : ops::{Deref, DerefMut},
3 : sync::Arc,
4 : };
5 :
6 : use anyhow::Context;
7 : use pageserver_api::{models::TimelineState, shard::TenantShardId};
8 : use remote_storage::DownloadError;
9 : use tokio::sync::OwnedMutexGuard;
10 : use tracing::{error, info, info_span, instrument, Instrument};
11 : use utils::{crashsafe, fs_ext, id::TimelineId, pausable_failpoint};
12 :
13 : use crate::{
14 : config::PageServerConf,
15 : task_mgr::{self, TaskKind},
16 : tenant::{
17 : metadata::TimelineMetadata,
18 : remote_timeline_client::{PersistIndexPartWithDeletedFlagError, RemoteTimelineClient},
19 : CreateTimelineCause, DeleteTimelineError, MaybeDeletedIndexPart, Tenant,
20 : TenantManifestError, TimelineOrOffloaded,
21 : },
22 : virtual_file::MaybeFatalIo,
23 : };
24 :
25 : use super::{Timeline, TimelineResources};
26 :
27 : /// Mark timeline as deleted in S3 so we won't pick it up next time
28 : /// during attach or pageserver restart.
29 : /// See comment in persist_index_part_with_deleted_flag.
30 0 : async fn set_deleted_in_remote_index(
31 0 : remote_client: &Arc<RemoteTimelineClient>,
32 0 : ) -> Result<(), DeleteTimelineError> {
33 0 : let res = remote_client.persist_index_part_with_deleted_flag().await;
34 0 : match res {
35 : // If we (now, or already) marked it successfully as deleted, we can proceed
36 0 : Ok(()) | Err(PersistIndexPartWithDeletedFlagError::AlreadyDeleted(_)) => (),
37 : // Bail out otherwise
38 : //
39 : // AlreadyInProgress shouldn't happen, because the 'delete_lock' prevents
40 : // two tasks from performing the deletion at the same time. The first task
41 : // that starts deletion should run it to completion.
42 0 : Err(e @ PersistIndexPartWithDeletedFlagError::AlreadyInProgress(_))
43 0 : | Err(e @ PersistIndexPartWithDeletedFlagError::Other(_)) => {
44 0 : return Err(DeleteTimelineError::Other(anyhow::anyhow!(e)));
45 : }
46 : }
47 0 : Ok(())
48 0 : }
49 :
50 : /// Grab the compaction and gc locks, and actually perform the deletion.
51 : ///
52 : /// The locks prevent GC or compaction from running at the same time. The background tasks do not
53 : /// register themselves with the timeline it's operating on, so it might still be running even
54 : /// though we called `shutdown_tasks`.
55 : ///
56 : /// Note that there are still other race conditions between
57 : /// GC, compaction and timeline deletion. See
58 : /// <https://github.com/neondatabase/neon/issues/2671>
59 : ///
60 : /// No timeout here, GC & Compaction should be responsive to the
61 : /// `TimelineState::Stopping` change.
62 : // pub(super): documentation link
63 4 : pub(super) async fn delete_local_timeline_directory(
64 4 : conf: &PageServerConf,
65 4 : tenant_shard_id: TenantShardId,
66 4 : timeline: &Timeline,
67 4 : ) {
68 4 : // Always ensure the lock order is compaction -> gc.
69 4 : let compaction_lock = timeline.compaction_lock.lock();
70 4 : let _compaction_lock = crate::timed(
71 4 : compaction_lock,
72 4 : "acquires compaction lock",
73 4 : std::time::Duration::from_secs(5),
74 4 : )
75 4 : .await;
76 :
77 4 : let gc_lock = timeline.gc_lock.lock();
78 4 : let _gc_lock = crate::timed(
79 4 : gc_lock,
80 4 : "acquires gc lock",
81 4 : std::time::Duration::from_secs(5),
82 4 : )
83 4 : .await;
84 :
85 : // NB: storage_sync upload tasks that reference these layers have been cancelled
86 : // by the caller.
87 :
88 4 : let local_timeline_directory = conf.timeline_path(&tenant_shard_id, &timeline.timeline_id);
89 4 :
90 4 : // NB: This need not be atomic because the deleted flag in the IndexPart
91 4 : // will be observed during tenant/timeline load. The deletion will be resumed there.
92 4 : //
93 4 : // ErrorKind::NotFound can happen e.g. if we race with tenant detach, because,
94 4 : // no locks are shared.
95 4 : tokio::fs::remove_dir_all(local_timeline_directory)
96 4 : .await
97 4 : .or_else(fs_ext::ignore_not_found)
98 4 : .fatal_err("removing timeline directory");
99 4 :
100 4 : // Make sure previous deletions are ordered before mark removal.
101 4 : // Otherwise there is no guarantee that they reach the disk before mark deletion.
102 4 : // So its possible for mark to reach disk first and for other deletions
103 4 : // to be reordered later and thus missed if a crash occurs.
104 4 : // Note that we dont need to sync after mark file is removed
105 4 : // because we can tolerate the case when mark file reappears on startup.
106 4 : let timeline_path = conf.timelines_path(&tenant_shard_id);
107 4 : crashsafe::fsync_async(timeline_path)
108 4 : .await
109 4 : .fatal_err("fsync after removing timeline directory");
110 4 :
111 4 : info!("finished deleting layer files, releasing locks");
112 4 : }
113 :
114 : /// It is important that this gets called when DeletionGuard is being held.
115 : /// For more context see comments in [`make_timeline_delete_guard`]
116 0 : async fn remove_maybe_offloaded_timeline_from_tenant(
117 0 : tenant: &Tenant,
118 0 : timeline: &TimelineOrOffloaded,
119 0 : _: &DeletionGuard, // using it as a witness
120 0 : ) -> anyhow::Result<()> {
121 0 : // Remove the timeline from the map.
122 0 : // This observes the locking order between timelines and timelines_offloaded
123 0 : let mut timelines = tenant.timelines.lock().unwrap();
124 0 : let mut timelines_offloaded = tenant.timelines_offloaded.lock().unwrap();
125 0 : let offloaded_children_exist = timelines_offloaded
126 0 : .iter()
127 0 : .any(|(_, entry)| entry.ancestor_timeline_id == Some(timeline.timeline_id()));
128 0 : let children_exist = timelines
129 0 : .iter()
130 0 : .any(|(_, entry)| entry.get_ancestor_timeline_id() == Some(timeline.timeline_id()));
131 0 : // XXX this can happen because of race conditions with branch creation.
132 0 : // We already deleted the remote layer files, so it's probably best to panic.
133 0 : if children_exist || offloaded_children_exist {
134 0 : panic!("Timeline grew children while we removed layer files");
135 0 : }
136 0 :
137 0 : match timeline {
138 0 : TimelineOrOffloaded::Timeline(timeline) => {
139 0 : timelines.remove(&timeline.timeline_id).expect(
140 0 : "timeline that we were deleting was concurrently removed from 'timelines' map",
141 0 : );
142 0 : }
143 0 : TimelineOrOffloaded::Offloaded(timeline) => {
144 0 : let offloaded_timeline = timelines_offloaded
145 0 : .remove(&timeline.timeline_id)
146 0 : .expect("timeline that we were deleting was concurrently removed from 'timelines_offloaded' map");
147 0 : offloaded_timeline.delete_from_ancestor_with_timelines(&timelines);
148 0 : }
149 : }
150 :
151 0 : drop(timelines_offloaded);
152 0 : drop(timelines);
153 0 :
154 0 : Ok(())
155 0 : }
156 :
157 : /// Orchestrates timeline shut down of all timeline tasks, removes its in-memory structures,
158 : /// and deletes its data from both disk and s3.
159 : /// The sequence of steps:
160 : /// 1. Set deleted_at in remote index part.
161 : /// 2. Create local mark file.
162 : /// 3. Delete local files except metadata (it is simpler this way, to be able to reuse timeline initialization code that expects metadata)
163 : /// 4. Delete remote layers
164 : /// 5. Delete index part
165 : /// 6. Delete meta, timeline directory
166 : /// 7. Delete mark file
167 : ///
168 : /// It is resumable from any step in case a crash/restart occurs.
169 : /// There are two entrypoints to the process:
170 : /// 1. [`DeleteTimelineFlow::run`] this is the main one called by a management api handler.
171 : /// 2. [`DeleteTimelineFlow::resume_deletion`] is called during restarts when local metadata is still present
172 : /// and we possibly neeed to continue deletion of remote files.
173 : ///
174 : /// Note the only other place that messes around timeline delete mark is the logic that scans directory with timelines during tenant load.
175 : #[derive(Default)]
176 : pub enum DeleteTimelineFlow {
177 : #[default]
178 : NotStarted,
179 : InProgress,
180 : Finished,
181 : }
182 :
183 : impl DeleteTimelineFlow {
184 : // These steps are run in the context of management api request handler.
185 : // Long running steps are continued to run in the background.
186 : // NB: If this fails half-way through, and is retried, the retry will go through
187 : // all the same steps again. Make sure the code here is idempotent, and don't
188 : // error out if some of the shutdown tasks have already been completed!
189 : #[instrument(skip_all)]
190 : pub async fn run(
191 : tenant: &Arc<Tenant>,
192 : timeline_id: TimelineId,
193 : ) -> Result<(), DeleteTimelineError> {
194 : super::debug_assert_current_span_has_tenant_and_timeline_id();
195 :
196 : let (timeline, mut guard) =
197 : make_timeline_delete_guard(tenant, timeline_id, TimelineDeleteGuardKind::Delete)?;
198 :
199 : guard.mark_in_progress()?;
200 :
201 : // Now that the Timeline is in Stopping state, request all the related tasks to shut down.
202 : if let TimelineOrOffloaded::Timeline(timeline) = &timeline {
203 : timeline.shutdown(super::ShutdownMode::Hard).await;
204 : }
205 :
206 : tenant.gc_block.before_delete(&timeline.timeline_id());
207 :
208 0 : fail::fail_point!("timeline-delete-before-index-deleted-at", |_| {
209 0 : Err(anyhow::anyhow!(
210 0 : "failpoint: timeline-delete-before-index-deleted-at"
211 0 : ))?
212 0 : });
213 :
214 : let remote_client = match timeline.maybe_remote_client() {
215 : Some(remote_client) => remote_client,
216 : None => {
217 : let remote_client = tenant
218 : .build_timeline_client(timeline.timeline_id(), tenant.remote_storage.clone());
219 : let result = match remote_client
220 : .download_index_file(&tenant.cancel)
221 : .instrument(info_span!("download_index_file"))
222 : .await
223 : {
224 : Ok(r) => r,
225 : Err(DownloadError::NotFound) => {
226 : // Deletion is already complete
227 : tracing::info!("Timeline already deleted in remote storage");
228 : return Ok(());
229 : }
230 : Err(e) => {
231 : return Err(DeleteTimelineError::Other(anyhow::anyhow!(
232 : "error: {:?}",
233 : e
234 : )));
235 : }
236 : };
237 : let index_part = match result {
238 : MaybeDeletedIndexPart::Deleted(p) => {
239 : tracing::info!("Timeline already set as deleted in remote index");
240 : p
241 : }
242 : MaybeDeletedIndexPart::IndexPart(p) => p,
243 : };
244 : let remote_client = Arc::new(remote_client);
245 :
246 : remote_client
247 : .init_upload_queue(&index_part)
248 : .map_err(DeleteTimelineError::Other)?;
249 : remote_client.shutdown().await;
250 : remote_client
251 : }
252 : };
253 : set_deleted_in_remote_index(&remote_client).await?;
254 :
255 0 : fail::fail_point!("timeline-delete-before-schedule", |_| {
256 0 : Err(anyhow::anyhow!(
257 0 : "failpoint: timeline-delete-before-schedule"
258 0 : ))?
259 0 : });
260 :
261 : Self::schedule_background(
262 : guard,
263 : tenant.conf,
264 : Arc::clone(tenant),
265 : timeline,
266 : remote_client,
267 : );
268 :
269 : Ok(())
270 : }
271 :
272 0 : fn mark_in_progress(&mut self) -> anyhow::Result<()> {
273 0 : match self {
274 0 : Self::Finished => anyhow::bail!("Bug. Is in finished state"),
275 0 : Self::InProgress { .. } => { /* We're in a retry */ }
276 0 : Self::NotStarted => { /* Fresh start */ }
277 : }
278 :
279 0 : *self = Self::InProgress;
280 0 :
281 0 : Ok(())
282 0 : }
283 :
284 : /// Shortcut to create Timeline in stopping state and spawn deletion task.
285 : #[instrument(skip_all, fields(%timeline_id))]
286 : pub(crate) async fn resume_deletion(
287 : tenant: Arc<Tenant>,
288 : timeline_id: TimelineId,
289 : local_metadata: &TimelineMetadata,
290 : remote_client: RemoteTimelineClient,
291 : ) -> anyhow::Result<()> {
292 : // Note: here we even skip populating layer map. Timeline is essentially uninitialized.
293 : // RemoteTimelineClient is the only functioning part.
294 : let timeline = tenant
295 : .create_timeline_struct(
296 : timeline_id,
297 : local_metadata,
298 : None, // Ancestor is not needed for deletion.
299 : TimelineResources {
300 : remote_client,
301 : pagestream_throttle: tenant.pagestream_throttle.clone(),
302 : pagestream_throttle_metrics: tenant.pagestream_throttle_metrics.clone(),
303 : l0_flush_global_state: tenant.l0_flush_global_state.clone(),
304 : },
305 : // Important. We dont pass ancestor above because it can be missing.
306 : // Thus we need to skip the validation here.
307 : CreateTimelineCause::Delete,
308 : crate::tenant::CreateTimelineIdempotency::FailWithConflict, // doesn't matter what we put here
309 : )
310 : .context("create_timeline_struct")?;
311 :
312 : let mut guard = DeletionGuard(
313 : Arc::clone(&timeline.delete_progress)
314 : .try_lock_owned()
315 : .expect("cannot happen because we're the only owner"),
316 : );
317 :
318 : // We meed to do this because when console retries delete request we shouldnt answer with 404
319 : // because 404 means successful deletion.
320 : {
321 : let mut locked = tenant.timelines.lock().unwrap();
322 : locked.insert(timeline_id, Arc::clone(&timeline));
323 : }
324 :
325 : guard.mark_in_progress()?;
326 :
327 : let remote_client = timeline.remote_client.clone();
328 : let timeline = TimelineOrOffloaded::Timeline(timeline);
329 : Self::schedule_background(guard, tenant.conf, tenant, timeline, remote_client);
330 :
331 : Ok(())
332 : }
333 :
334 0 : fn schedule_background(
335 0 : guard: DeletionGuard,
336 0 : conf: &'static PageServerConf,
337 0 : tenant: Arc<Tenant>,
338 0 : timeline: TimelineOrOffloaded,
339 0 : remote_client: Arc<RemoteTimelineClient>,
340 0 : ) {
341 0 : let tenant_shard_id = timeline.tenant_shard_id();
342 0 : let timeline_id = timeline.timeline_id();
343 0 :
344 0 : task_mgr::spawn(
345 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
346 0 : TaskKind::TimelineDeletionWorker,
347 0 : tenant_shard_id,
348 0 : Some(timeline_id),
349 0 : "timeline_delete",
350 0 : async move {
351 0 : if let Err(err) = Self::background(guard, conf, &tenant, &timeline, remote_client).await {
352 : // Only log as an error if it's not a cancellation.
353 0 : if matches!(err, DeleteTimelineError::Cancelled) {
354 0 : info!("Shutdown during timeline deletion");
355 : }else {
356 0 : error!("Error: {err:#}");
357 : }
358 0 : if let TimelineOrOffloaded::Timeline(timeline) = timeline {
359 0 : timeline.set_broken(format!("{err:#}"))
360 0 : }
361 0 : };
362 0 : Ok(())
363 0 : }
364 0 : .instrument(tracing::info_span!(parent: None, "delete_timeline", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),timeline_id=%timeline_id)),
365 : );
366 0 : }
367 :
368 0 : async fn background(
369 0 : mut guard: DeletionGuard,
370 0 : conf: &PageServerConf,
371 0 : tenant: &Tenant,
372 0 : timeline: &TimelineOrOffloaded,
373 0 : remote_client: Arc<RemoteTimelineClient>,
374 0 : ) -> Result<(), DeleteTimelineError> {
375 0 : fail::fail_point!("timeline-delete-before-rm", |_| {
376 0 : Err(anyhow::anyhow!("failpoint: timeline-delete-before-rm"))?
377 0 : });
378 :
379 : // Offloaded timelines have no local state
380 : // TODO: once we persist offloaded information, delete the timeline from there, too
381 0 : if let TimelineOrOffloaded::Timeline(timeline) = timeline {
382 0 : delete_local_timeline_directory(conf, tenant.tenant_shard_id, timeline).await;
383 0 : }
384 :
385 0 : fail::fail_point!("timeline-delete-after-rm", |_| {
386 0 : Err(anyhow::anyhow!("failpoint: timeline-delete-after-rm"))?
387 0 : });
388 :
389 0 : remote_client.delete_all().await?;
390 :
391 0 : pausable_failpoint!("in_progress_delete");
392 :
393 0 : remove_maybe_offloaded_timeline_from_tenant(tenant, timeline, &guard).await?;
394 :
395 : // This is susceptible to race conditions, i.e. we won't continue deletions if there is a crash
396 : // between the deletion of the index-part.json and reaching of this code.
397 : // So indeed, the tenant manifest might refer to an offloaded timeline which has already been deleted.
398 : // However, we handle this case in tenant loading code so the next time we attach, the issue is
399 : // resolved.
400 0 : tenant.store_tenant_manifest().await.map_err(|e| match e {
401 0 : TenantManifestError::Cancelled => DeleteTimelineError::Cancelled,
402 0 : _ => DeleteTimelineError::Other(e.into()),
403 0 : })?;
404 :
405 0 : *guard = Self::Finished;
406 0 :
407 0 : Ok(())
408 0 : }
409 :
410 0 : pub(crate) fn is_not_started(&self) -> bool {
411 0 : matches!(self, Self::NotStarted)
412 0 : }
413 : }
414 :
415 : #[derive(Copy, Clone, PartialEq, Eq)]
416 : pub(super) enum TimelineDeleteGuardKind {
417 : Offload,
418 : Delete,
419 : }
420 :
421 4 : pub(super) fn make_timeline_delete_guard(
422 4 : tenant: &Tenant,
423 4 : timeline_id: TimelineId,
424 4 : guard_kind: TimelineDeleteGuardKind,
425 4 : ) -> Result<(TimelineOrOffloaded, DeletionGuard), DeleteTimelineError> {
426 4 : // Note the interaction between this guard and deletion guard.
427 4 : // Here we attempt to lock deletion guard when we're holding a lock on timelines.
428 4 : // This is important because when you take into account `remove_timeline_from_tenant`
429 4 : // we remove timeline from memory when we still hold the deletion guard.
430 4 : // So here when timeline deletion is finished timeline wont be present in timelines map at all
431 4 : // which makes the following sequence impossible:
432 4 : // T1: get preempted right before the try_lock on `Timeline::delete_progress`
433 4 : // T2: do a full deletion, acquire and drop `Timeline::delete_progress`
434 4 : // T1: acquire deletion lock, do another `DeleteTimelineFlow::run`
435 4 : // For more context see this discussion: `https://github.com/neondatabase/neon/pull/4552#discussion_r1253437346`
436 4 : let timelines = tenant.timelines.lock().unwrap();
437 4 : let timelines_offloaded = tenant.timelines_offloaded.lock().unwrap();
438 :
439 4 : let timeline = match timelines.get(&timeline_id) {
440 4 : Some(t) => TimelineOrOffloaded::Timeline(Arc::clone(t)),
441 0 : None => match timelines_offloaded.get(&timeline_id) {
442 0 : Some(t) => TimelineOrOffloaded::Offloaded(Arc::clone(t)),
443 0 : None => return Err(DeleteTimelineError::NotFound),
444 : },
445 : };
446 :
447 : // Ensure that there are no child timelines, because we are about to remove files,
448 : // which will break child branches
449 4 : let mut children = Vec::new();
450 4 : if guard_kind == TimelineDeleteGuardKind::Delete {
451 0 : children.extend(timelines_offloaded.iter().filter_map(|(id, entry)| {
452 0 : (entry.ancestor_timeline_id == Some(timeline_id)).then_some(*id)
453 0 : }));
454 4 : }
455 8 : children.extend(timelines.iter().filter_map(|(id, entry)| {
456 8 : (entry.get_ancestor_timeline_id() == Some(timeline_id)).then_some(*id)
457 8 : }));
458 4 :
459 4 : if !children.is_empty() {
460 0 : return Err(DeleteTimelineError::HasChildren(children));
461 4 : }
462 4 :
463 4 : // Note that using try_lock here is important to avoid a deadlock.
464 4 : // Here we take lock on timelines and then the deletion guard.
465 4 : // At the end of the operation we're holding the guard and need to lock timelines map
466 4 : // to remove the timeline from it.
467 4 : // Always if you have two locks that are taken in different order this can result in a deadlock.
468 4 :
469 4 : let delete_progress = Arc::clone(timeline.delete_progress());
470 4 : let delete_lock_guard = match delete_progress.try_lock_owned() {
471 4 : Ok(guard) => DeletionGuard(guard),
472 : Err(_) => {
473 : // Unfortunately if lock fails arc is consumed.
474 0 : return Err(DeleteTimelineError::AlreadyInProgress(Arc::clone(
475 0 : timeline.delete_progress(),
476 0 : )));
477 : }
478 : };
479 :
480 4 : if guard_kind == TimelineDeleteGuardKind::Delete {
481 0 : if let TimelineOrOffloaded::Timeline(timeline) = &timeline {
482 0 : timeline.set_state(TimelineState::Stopping);
483 0 : }
484 4 : }
485 :
486 4 : Ok((timeline, delete_lock_guard))
487 4 : }
488 :
489 : pub(super) struct DeletionGuard(OwnedMutexGuard<DeleteTimelineFlow>);
490 :
491 : impl Deref for DeletionGuard {
492 : type Target = DeleteTimelineFlow;
493 :
494 0 : fn deref(&self) -> &Self::Target {
495 0 : &self.0
496 0 : }
497 : }
498 :
499 : impl DerefMut for DeletionGuard {
500 0 : fn deref_mut(&mut self) -> &mut Self::Target {
501 0 : &mut self.0
502 0 : }
503 : }
|