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